【问题标题】:html.dropdownlistfor not posting back to controller in formhtml.dropdownlistfor 不以表单回发到控制器
【发布时间】:2015-06-13 16:38:55
【问题描述】:

我在 MVC 应用程序中有一个表单。回发返回模型,其中填充了除下拉列表的值之外的所有值。这是我为下拉菜单写的代码,我到底哪里出错了?

型号:

public class ViewModel : Model 
{
    public Dictionary<int, string> ServiceFocusList { get; set; }
    public int ServiceFocus { get; set; }
}

查看:

@using
(Html.BeginForm("SaveServiceRequest","ServiceRequest",FormMethod.Post))
{
    var AddLotLink = Url.Action("SaveServiceRequest", "ServiceRequest");
    var labelCol = "control-label col-md-4";
    @Html.LabelFor(model => model.ServiceFocusList, new { @class = @labelCol })
    @Html.ValidationMessageFor(model => model.ServiceFocusList)
    @Html.DropDownListFor(model => model.ServiceFocusList ,new SelectList(Model.ServiceFocusList,"Key",
     "Value", Model.ServiceFocus), "Select a Service Focus")
    <input type="submit" id="AddLotBtn" value="Add A Lot" class="saveDraft btn btn-default" urllink="@AddLotLink" />
}

控制器:

public ActionResult SaveServiceRequest(ViewModel model, long? lotId)
{
    //At this point both model.ServiceFocusList and model.ServiceFocus are null
    ServiceRequestSupport.SaveServiceRequest(model);
    RedirectToAction("CreateLotOffSR", "Lot", new {area = "Lot", model.ID});
}

【问题讨论】:

  • 你的 ddl 正在填充?您不需要控制器上的 FormCollection 来收集发布在表单上的信息吗?

标签: c# asp.net asp.net-mvc razor html.dropdownlistfor


【解决方案1】:

DropDownListFor 的第一个参数应该标识包含所选值的属性。你想要这个:

@Html.DropDownListFor(model => model.ServiceFocus, new SelectList(Model.ServiceFocusList,"Key",
 "Value", Model.ServiceFocus), "Select a Service Focus")

【讨论】:

    【解决方案2】:

    将视图中的 DropdownList 更改为以下,您将其绑定到字典而不是保存所选值的属性。

    @Html.DropDownListFor(model => model.ServiceFocus ,new SelectList(Model.ServiceFocusList,"Key",
         "Value", Model.ServiceFocus), "Select a Service Focus")
    

    【讨论】:

      猜你喜欢
      • 2015-11-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2016-10-03
      • 2013-11-10
      • 1970-01-01
      相关资源
      最近更新 更多