以下是基於this blogpost的最小示例。爲了演示目的,我已經命名了我的模型Foo
。所以,每當你讀到這個時,這應該是你的模型與文件,名稱和貓屬性。
首先,將https://www.nuget.org/packages/BeginCollectionItem/
添加到您的項目中。
然後,將一個局部視圖添加到您的視圖文件夾。我叫我的「_AddFile.cshtml」:
@model WebApplication2.Models.Foo
@using (Html.BeginCollectionItem("files"))
{
<div class="form-horizontal">
<fieldset>
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
</div>
@Html.LabelFor(model => model.Cat, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Cat, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
</fieldset>
</div>
}
注意,Html.BeginCollectionItem("files")
,這是創建集合,稍後組合在一起,並綁定到一個名爲「文件」的模式。
我們的控制器是這樣的:
public ActionResult Index()
{
//Initialize the view with an empty default entry
var vm = new List<Foo> {
new Models.Foo {
Cat ="foo",
Name =" bar"
}
};
return View(vm);
}
//this calls your partial view and initializes an empty model
public PartialViewResult AddFile()
{
return PartialView("_AddFile", new Foo());
}
//note "files" name? The same as our collection name specified earlier
[HttpPost]
public ActionResult PostFiles(IEnumerable<Foo> files)
{
//do whatever you want with your posted model here
return View();
}
在您看來,使用這種形式:
@model IEnumerable<WebApplication2.Models.Foo>
@using (Html.BeginForm("PostFiles","Home", FormMethod.Post))
{
<div id="FileEditor">
@foreach (var item in Model)
{
Html.RenderPartial("_AddFile", item);
}
</div>
<div>
@Html.ActionLink("Add File", "AddFile", null, new { id = "addFile" }) <input type="submit" value="Finished" />
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(function() {
$("#addFile").click(function() {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#FileEditor").append(html); }
});
return false;
});
})
</script>
}
foreach循環使每個模型項的局部視圖,在我們的例子只是一個用一個默認條目。
JavaScript循環然後調用我們的PartialView並在現有的模板下呈現一個空模板。
調用提交,然後讓你處理你的文件在任何你想要的方式:
關鍵字這裏是'編輯Template'或「部分視圖」。 – jAC