【问题标题】:Changing the model field with TextBoxFor and passing the model to the controller使用 TextBoxFor 更改模型字段并将模型传递给控制器
【发布时间】:2021-05-22 20:15:01
【问题描述】:

我有一个具有视图模型属性的模型:

public class FilterModel
{
    [DisplayName("Start")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{MM/dd/yyyy HH:mm}")] 
    public DateTime StartDate { get; set; }

    [DisplayName("End")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{MM/dd/yyyy HH:mm}")]
    public DateTime EndDate { get; set; }

    public bool ShowActive { get; set; }
}

我在使用TextBoxFor的模型上更新StartDateEndDate

@using (Html.BeginForm("ApplyFilter", "Shipment", FormMethod.Post))
{
   <div class="input-group">
      <button type="submit" class="btn btn-default btn-sm" style="margin: 3px">
           <i class="fa fa-check"></i>
      </button>
      @Html.TextBoxFor(m => m.Filter.StartDate,  new { @minlength = "4", @maxlength = "20", @style = "margin: 3px; border: solid 1px #d5d5d5;" })
      @Html.TextBoxFor(m => m.Filter.EndDate, new { @minlength = "4", @maxlength = "20", @style = "margin: 3px; border: solid 1px #d5d5d5;" })
  </div>
}

控制器ApplyFilter中的方法:

public ActionResult ApplyFilter(FilterModel filter)
{
   var vm = Load(filter);
   return View("Index", vm);
}

属性StartDateEndDate 已正确更新,但属性ShowActive 始终设置为False。调用ApplyFilter 方法时,属性ShowActive 不会将其在视图中的当前值传递给控制器​​。

【问题讨论】:

    标签: c# html asp.net-mvc


    【解决方案1】:

    您必须将 ShowActive 添加到您的视图中

    @using (Html.BeginForm("ApplyFilter", "Shipment", FormMethod.Post))
    {
     
    @Html.HiddenFor(m => m.ShowActive)
    ....
    }
    

    【讨论】:

      【解决方案2】:

      您错过了 View 上的 ShowActive:

      您可以添加:

      <div class="checkbox">
         @Html.CheckBoxFor(x => x.ShowActive, new { htmlAttributes = new { @type = "checkbox", @id = "checkbox-showactive" } })
         <label for="checkbox-showactive"> Active</label>
      </div>
      

      如果您想处理对用户隐藏的属性:

      @model FilterModel
      ---
      @Html.HiddenFor(m => Model.ShowActive)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-03
        • 2016-03-01
        • 1970-01-01
        • 2019-10-18
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        相关资源
        最近更新 更多