我在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});
}
答案 0 :(得分:1)
DropDownListFor的第一个参数应该标识包含所选值的属性。你想要这个:
@Html.DropDownListFor(model => model.ServiceFocus, new SelectList(Model.ServiceFocusList,"Key",
"Value", Model.ServiceFocus), "Select a Service Focus")
答案 1 :(得分:0)
在视图中将DropdownList更改为以下内容,您将其绑定到字典而不是包含所选值的属性。
@Html.DropDownListFor(model => model.ServiceFocus ,new SelectList(Model.ServiceFocusList,"Key",
"Value", Model.ServiceFocus), "Select a Service Focus")