如何使用ModelBinding将SelectedItem绑定到我的模型?
首先,我创建一个简单模型:
public class Element
{
public string Name { get; set; }
public int Value { get; set; }
}
public class MyModel
{
public Guid ContactID { get; set; }
public List<Element> Collection { get; set; }
public IEnumerable<SelectListItem> SelectList
{
get
{
return Collection.Select
(
e => new SelectListItem
{
Text = e.Name,
Value = e.Value.ToString()
}
);
}
}
public Element SelectedElement { get; set; }
}
然后在我的控制器中将其初始化:
public ActionResult Test()
{
var model = new MyModel {ContactID = Guid.NewGuid(), Collection = new List<Element>() };
var rand = new Random();
while (model.Collection.Count < 10)
{
var number = rand.Next(100);
model.Collection.Add(new Element {Value = number, Name = number.ToString()});
}
return View(model);
}
并在我的视图中显示它:
@using (Html.BeginForm("TestPostBack", "Home"))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>MyModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.ContactID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ContactID, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Collection, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.SelectedElement, Model.SelectList)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
在表单上按下提交按钮时,我想在控制器上点击TestPostBack
。那也没问题。但是,如何在模型中填写SelectedElement
属性?我希望它是下拉菜单中所选项目的值。
public ActionResult TestPostBack(MyModel model)
{
throw new NotImplementedException();
}
答案 0 :(得分:1)
我认为将整个对象取回并不是一件容易的事。不是没有,只是没有容易。这里的问题是,与HTML select元素相对应的下拉列表仅回发了选项的选定值,而没有文本。因此,人们可能会想到拦截表单发布请求并在其中添加文本,但这感觉有些hacker。
最直接的方法是只取回价值:
public class MyModel
{
...
public int SelectedElementValue { get; set; }
}
Html.DropDownListFor(model => model.SelectedElementValue, Model.SelectList)
然后按值在元素之间查找对象。希望他的价值是独一无二的:
public ActionResult TestPostBack(MyModel model)
{
// load list of elements
Element selectedElement = //look up element by model.SelectedElementValue
}