我的目標是允許用戶在創建和/或編輯評論時將目標(子級)添加到評論(父級)。我有這個主要工作,所以我正在尋找兩個問題的答案A.我怎麼能做到這一點,更好,更清潔,和B.當我編輯父爲什麼不能保存新添加的孩子。我的猜測是A的答案會使B過時。謝謝您的幫助。在asp.net MVC3 EF4.1中創建父級創建時的動態列表
下面是一些代碼亮點和我的工作草圖解決方案,您可以在下面下載。
public ActionResult Create()
{
var review = new Review();
review.Goals.Add(new Goal());
return View(review);
}
//
// GET: /Reviews/Edit/5
public ActionResult Edit(int id)
{
return View(reviewRepository.AllIncluding(review => review.Goals).Single(review => review.ReviewID == id));
}
這是非常基本的,在這裏沒有什麼奇特的基本。
這裏是我的createoredit形式與jQuery的爲Ajax調用
<div class="editor-label">
@Html.LabelFor(model => model.ReviewName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ReviewName)
@Html.ValidationMessageFor(model => model.ReviewName)
<div id="goals">
@Html.EditorFor(model => model.Goals)
</div>
@Html.ActionLink("Add another...", "NewGoal", null, new { id = "addItem" })
<script type="text/javascript">
$("#addItem").click(function() {
$.ajax({
url: this.href,
data: "index=" + getLastIndex() + "&parentID=" + getParentID(),
cache: false,
success: function (html) {
alert(html);
$("#goals").append(html);
}
});
return false;
});
function getParentID() {
var val = $('#ReviewID').val();
if (val == null)
return 0;
else
return val;
}
function getLastIndex() {
return $('input[name=Goals.Index]:last').val();
}
</script>
Ajax請求接收的局部視圖
public PartialViewResult NewGoal(int? index, int? parentID)
{
ViewBag.Index = index + 1;
ViewBag.ParentID = parentID;
return PartialView("../Shared/NewGoal", new Goal());
}
,這裏是什麼部分的樣子。在我的項目中,你會看到我有一個html helper的開始,它使用正確的索引來建立起來,現在它的模型名被硬編碼,因爲這只是myscratch項目,我相信有一個更好的方法去做這個。
<input name="Goals.Index" value="0" type="hidden">
<input id="Goals_0__GoalID" name="Goals[0].GoalID" value="0" type="hidden" data-val-required="The GoalID field is required." data-val-number="The field GoalID must be a number." data-val="true">
<input id="Goals_0__ReviewID" name="Goals[0].ReviewID" value="0" type="hidden" data-val-required="The ReviewID field is required." data-val-number="The field ReviewID must be a number." data-val="true">
<div class="editor-label">
<label for="Goals_0__GoalName">GoalName</label>
</div>
<div class="editor-field">
<input id="Goals_0__GoalName" class="text-box single-line" name="Goals[0].GoalName" value="" type="text">
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Goals[0].GoalName"></span>
</div>
Visual Studio解決方案http://dl.dropbox.com/u/29534952/RelationScratch.zip
是我的解決方案嗎?如果沒有,告訴我什麼是不工作,所以我可以幫助你更多。 –