我有一个如下所示的控制器:
public async Task<ActionResult> CreateProduct([Bind(Include = "Id,MyCollection")] MyClass myClass)
这是观点:
<div class="form-group">
@Html.LabelFor(model => model.Id, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Id)
@Html.ValidationMessageFor(model => model.Id)
</div>
</div>
<table>
<tr>
<th>@Html.LabelFor(model => model.MyCollection.First().A)</th>
<th>@Html.LabelFor(model => model.MyCollection.First().B)</th>
<th>@Html.LabelFor(model => model.MyCollection.First().C)</th>
</tr>
@foreach (var item in this.Model.Warnings)
{
<tr>
<td>@Html.ValueFor(model => item.A)</td>
<td>@Html.EditorFor(model => item.B)</td>
<td>@Html.EditorFor(model => item.C)</td>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
当我单击“保存”时,它会发布到操作但仅将Id分配给对象,而不是myCollection。
将这些集合发布到控制器时,我需要做些什么来包含该集合?
更新
模型由实体框架
public abstract partial class MyBaseClass
{
public Module()
{
this.MyCollection= new HashSet<Warning>();
}
public int Id { get; set; }
public virtual ICollection<Warning> MyCollection { get; set; }
}
public partial class MyClass : MyBaseClass
{
// more properties that aren't used on this controller
}
答案 0 :(得分:0)
为了使其工作,您需要了解ASP.NET MVC如何处理List
的模型绑定。 Scott Hansleman有good post explaining this。
由于你的问题在你所处理的实际属性方面相当模糊,我把一个成功绑定到列表的小例子放在一起:
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
//Initial test data
var zoo = new Zoo()
{
Id = 1,
Name = "Vilas Zoo",
Animals = new List<Animal>()
{
new Animal() {
Id = 1,
Name = "Red Panda"
},
new Animal() {
Id = 2,
Name = "Sloth"
},
new Animal() {
Id = 3,
Name = "Badger"
},
}
};
return View(zoo);
}
[HttpPost]
public JsonResult Index(Zoo zoo)
{
return Json(zoo);
}
}
public class Zoo
{
public int Id { get; set; }
public string Name { get; set; }
public List<Animal> Animals { get; set; }
}
public class Animal
{
public int Id { get; set; }
public string Name { get; set; }
}
<h1>@Model.Id - @Model.Name</h1>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
for (var i=0; i < Model.Animals.Count; i++)
{
@Html.EditorFor(m => Model.Animals[i])
}
<button type="submit">Save it, yo</button>
}
注意我是如何使用for
循环而不是foreach
的,并且在调用EditorFor
时正在使用循环的实际索引。