找到了解决办法,而是一个非常难看的一个,看到在底部,有人可以改善这个解决方案在MVC,而“创造”到模型?动态添加ICollection的项目
所以我有一个假人模型像这样的
public class TestModel
{
public int TestModelID { get; set; }
public string Name { get; set; }
}
而另一个像这样的
public class Collector
{
public int CollectorID { get; set; }
public string CollectorString { get; set; }
public ICollection<TestModel> MyList { get; set; }
}
我想(在简单的CRUD风格)创建一个新的对象收藏家和填充(后来与动态添加新的领域,现在只有一个)ICollection中。 这是我的看法
@model TestApplication.Models.Collector
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Collector</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.CollectorString, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CollectorString, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CollectorString, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => Model.MyList.ToList()[0].Name)
<div class="col-md-10">
@Html.EditorFor(model => model.MyList.ToList()[0].Name, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
而且控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Collector collector)
{
if (ModelState.IsValid)
{
db.Collectors.Add(collector);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(collector);
}
这是生成的HTML代码(只有我希望有关部分)
<div class="form-group">
<label for="">Name</label>
<div class="col-md-10">
<input class="form-control text-box single-line" name="[0].Name" type="text" value="" />
</div>
</div>
然而,MyList
控制器时创建总是空的,为什么? (是的,我知道Haackeds博客文章,仍然无法弄清楚,为什么它不工作)
所以问题是,这条线
@Html.EditorFor(model => model.MyList.ToList()[0].Name, new { htmlAttributes = new { @class = "form-control" } })
虽然很推荐MVC使用,这产生这里
<input class="form-control text-box single-line" name="[0].Name" type="text" value="" />
这显然不工作。我如何获得剃刀改变[0].Name
到MyList[0].Name
?
**更新:** 所以我找到了解决办法,如果硬编码这个位置
<input class="form-control text-box single-line" name="MyList[0].Name" type="text" value="" />
控制器理解它,我不明白null
。如何用剃刀去解决呢?
你'Collector'应类包含一个构造函数和初始化'MyList'成为'MYLIST =新名单();' –
Monah
@RobertStettler是否考虑将ICollection更改为IList,以便您可以使用索引器。 ICollection在IList中没有索引器属性。我提供了一个解释的答案。 – Nkosi