Bind(Include =不能用于collection



我有一个控制器,看起来像下面:

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>

当我点击Save时,它发送到动作,但只有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
}

为了让这个工作,你需要了解ASP是如何. NET MVC处理List的模型绑定。Scott Hansleman有一篇很好的文章解释了这一点。

由于你的问题在你处理的实际属性方面相当模糊,我把一个成功绑定到列表的小例子放在一起:

h2控制器

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; }
}
<<h2>视图/h2>
<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时使用了循环的实际索引。

最新更新