找到了解決辦法,而是一個非常難看的一個,看到在底部,有人可以改善這個解決方案在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