我在这里完全不知所措,无法找到解决这个问题的方法。有人可以帮助提供一些代码:
我是mvc3的新手。以下是详细信息......
修改视图:
@model MVC3.Models.A
// I need to save collection values but can't use [] here to setup model binding.
// I have read about mapping collections but I already have a model A that is getting passed in.
//
@Html.EditorFor(model => model.Bs[0].Val)
型号:
public class A
{
public A()
{
this.Bs = new HashSet<B>();
}
public int Name { get; set; }
public virtual ICollection<B> Bs { get; set; } // Can't change this to ILIst because of above HashSet
- }
public class B
{
public int Val { get; set; }
public virtual A A { get; set; }
}
答案 0 :(得分:1)
您的模型在视图模型中具有循环引用。这不是默认模型绑定器支持的方案。我建议您始终在视图中使用编辑器模板。例如:
型号:
public class A
{
public int Name { get; set; }
public virtual ICollection<B> Bs { get; set; }
}
public class B
{
public int Val { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new A
{
Name = 123,
Bs = new[]
{
new B { Val = 1 },
new B { Val = 2 },
new B { Val = 3 },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(A a)
{
// The Bs collection will be properly bound here
return View(a);
}
}
查看(~/Views/Home/Index.cshtml
):
@model A
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
</div>
@Html.EditorFor(x => x.Bs)
<button type="submit">OK</button>
}
将为Bs集合的每个元素(~/Views/Home/EditorTemplates/B.cshtml
)呈现相应的编辑器模板:
@model B
<div>
@Html.LabelFor(x => x.Val)
@Html.EditorFor(x => x.Val)
</div>