html.dropdownlist用于不以表单形式回发到控制器
本文关键字:控制器 表单 dropdownlist 用于 html | 更新日期: 2023-09-27 18:34:26
>我在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});
}
DropDownListFor 的第一个参数应该标识包含所选值的属性。你想要这个:
@Html.DropDownListFor(model => model.ServiceFocus, new SelectList(Model.ServiceFocusList,"Key",
"Value", Model.ServiceFocus), "Select a Service Focus")
将视图中的下拉列表更改为以下内容,您将其绑定到字典而不是保存选定值的属性。
@Html.DropDownListFor(model => model.ServiceFocus ,new SelectList(Model.ServiceFocusList,"Key",
"Value", Model.ServiceFocus), "Select a Service Focus")