我有這個模型有另一個模型的列表。然後在我看來,我的表格爲我的主模型填充了幾個字段。但我希望這種形式也能夠添加其他類型的X模型,並且都是有線的,我想知道如何正確地做到這一點。具有模型列表的模型的MVC客戶端驗證
因此,這裏有我的兩個型號:
public class MyMainModel
{
public int MyMainId { get; set; }
[Required(ErrorMessage = "Groovy name required")]
[Display(Name = "MyMainModel's groovy name:")]
public string Name { get; set; }
public List<MySubModel> MySubModels { get; set; }
}
public class MySubModel
{
public int MySubId { get; set; }
[Required(ErrorMessage = "Cool name required")]
[Display(Name = "MySubModel's cool name:")]
public string Name { get; set; }
}
當我打我的控制器,我的「創造」的看法,我通過這個動作:
public ActionResult SomePageAboutCreating()
{
// [...] Some other stuff
return View(new MyMainModel());
}
現在這個發送到我的強類型查看:
@model myFunProject.WebModels.MyMainModel
<div>
<form id="my-create-form" onsubmit="CreateMyMainModel(this); return false;">
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="result" style="background-color: silver;">This is the operation result box</div>
<img class="loading" src="/Images/ajax-loader.gif" alt="Loading..." width="16" height="16" style="display: none;" />
<section>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
</section>
<!-- Here begins the fields for my list of "MySubModel" -->
@Html.EditorFor(x => x.MySubModels)
<!-- Here I'm thinking about a javascript that will add the previous fields X times so that the user can create "MyMainModel" as well as x times "MySubModel"... -->
<input type="submit" class="btn-send" id="my-create-form-submit" value="Send" />
</form>
</div>
所以我想我必須在這裏使用EditorTemplates ...所以我安裝在我的/ Views/EditorTemplates/MySub Models.cshtml(命名反對我「MyMainModel」的屬性),然後當我寫我的形式在那裏,我很困惑...
@model myFunProject.WebModels.MyMainModel
@*<section>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
</section>*@
所以在這裏我不知道要放什麼東西在這裏...我希望我的名稱屬性是「MySubModel」之一。當用戶看到這個表單時,比如說他會經歷這種情況:
- 輸入「MyMainModel」的名稱。
- 轉到其他人的名字框和在「MySubModel的第一個實例的名稱罷了。
- 然後,他會點擊一個特殊的按鈕,將操作DOM追加另一MySubModel.Name場。
- 他會寫在第二個「MySubModel」的名字。
- 他會點擊提交。
AJAX調用我擺在那裏我確定做配線,但我的困惑帶有我編寫的代碼編輯器模板,然後我有點想知道我將如何創建一個新的領域(第二個「MySubModel」例如...)。
任何幫助將不勝感激,我已經通過了許多關於這個主題的文章,但還沒有發現這種情況。謝謝!
編輯:
我會添加動作(過於簡化的版本,嘿嘿)由我的阿賈克斯提交表單時調用。
public ActionResult CreateMyMainModel(MyMainModel myMainModel) {
// [...] Do stuff like save to database...
// var aGroovyNAme = myMainModel.Name;
foreach(var mySubModel in myMainModel.MySubModels) {
// Here I would have the sub models available to manipulate...
// var aCoolName = mySubModel.Name;
}
return Content("ok");
}
的[ASP.Net MVC4綁定「創建視圖」到包含列表中選擇模型]可能的複製(http://stackoverflow.com/questions/12974957/asp-net-mvc4-bind-a-create-view-to-a-model-that-contains-list) – halfer 2016-02-14 21:36:49
我已經添加了一個dup建議基於來自@Savantes的回答。 – halfer 2016-02-14 21:37:09