I am trying to make an editor for an object in ASP.net MVC 3. It looks something like this:
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.foo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.foo)
@Html.ValidationMessageFor(model =&g开发者_Python百科t; model.foo)
</div>
@if (Model.Items.Count > 0)
{
<table>
@foreach (var ii in Model.Items)
{ @Html.EditorFor(item => ii) }
</table>
}
In this example, Items is a list of another kind of object. The problem is, when the model is posted back from being edited in the view, the data changes to Model.Items aren't there, while the data changes to Name and foo work. How can I make it so that the data for Items binds correctly?
Model class:
public class HomeControllerModel
{
public string Name { get; set; }
public string foo { get; set; }
public List<string> Items { get; set; }
public HomeControllerModel()
{
Items = new List<string>();
}
}
Controller class:
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var model = new HomeControllerModel();
model.Name = "LukLed";
model.foo = "bar";
model.Items.Add("AAA");
model.Items.Add("BBB");
model.Items.Add("CCC");
return View(model);
}
[HttpPost]
public ActionResult Index(HomeControllerModel model)
{
return View(model);
}
View:
@using MvcApplication4.Controllers
@model HomeControllerModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
<form action="/Home/Index" method="post">
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.foo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.foo)
@Html.ValidationMessageFor(model => model.foo)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Items)
</div>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
You don't have to iterate through Items
.
精彩评论