![](/img/trans.png)
[英]asp.net mvc 5 DropDownList nullable int default option not null
[英]ASP .Net MVC DropDownList bound to nullable field
我有一个下拉列表。 它不是必需的,因此后备字段可以为空。 但是,在加载表单时,下拉列表似乎正在将所选值设置为第一个id(顺序为第一个)。
我建立这样的选择列表项:
var servers = await Context.Servers.OrderBy(s => s.Name).ToListAsync();
servers.Insert(0, new Models.Server() { Id = Guid.Empty, Name = "SELECT ONE" });
return servers.Select(t => new SelectListItem()
{
Selected = t.Id == Guid.Empty ? true : false,
Text = t.Name,
Value = t.Id.ToString()
});
我这样渲染它:
@Html.DropDownListFor(m => m.ProductionEnvironment_ServerId, Model.ProductionEnvironment_Servers)
如果ServerId为null,则选择ID字段中的第一个顺序Guid。 如果我将ServerId设为不可为空,则下拉列表将变为必需的,而不应该为空。
在GET操作方法中,将呈现视图模型时将视图模型的ProductionEnvironment_ServerId
属性值设置为要选择的值。
public ActionResult Edit()
{
var vm = new YourViewModel(int id);
vm.ProductionEnvironment_Servers = servers.Select(s => new SelectListItem
{
Value = s.Id.ToString(),
Text = s.Name
});
//Set the value you want to be selected.
Guid guidWhichShouldBeSelected = GetSelectedGuidHereFromSomeWhere(id);
vm.ProductionEnvironment_ServerId = guidWhichShouldBeSelected;
return View(vm);
}
同样,在剃刀视图中,您可以使用对助手方法的覆盖将“选择”选项添加到选项列表中。 您无需从服务器端添加一个。
@Html.DropDownListFor(m => m.ProductionEnvironment_ServerId,
Model.ProductionEnvironment_Servers,"Select")
这将添加“ Select
”选项作为第一个选项。
提交表单时,在HttpPost
操作方法中,检查发布模型的ProductionEnvironment_ServerId
属性的值。 您将获得所选项目的值(引导),如果他们选择第一个“选择”选项,则为空。
[HttpPost]
public ActionResult Edit(YourViewModel model)
{
//check model.ProductionEnvironment_ServerId
// to do : Save and Redirect
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.