次の問題があります。
「Gifts」のコレクションがパラメーターとしてビューに渡されます。このコレクション内の各アイテムは、Model クラス "Gift" のオブジェクトです。このクラス内には、name と price の 2 つのプロパティしかありません。簡単にするために、クラスをコントローラー内に配置しました。
これはアクションメソッドです:
// GET: Order/CreateGift
[HttpGet]
public ActionResult CreateGift()
{
var initialData = new[]
{
new Gift{ Name = "Tricycle", Price = 69.95 },
new Gift{ Name = "PS4 game", Price = 29.99 },
new Gift{ Name = "Lazergun", Price = 49.99}
};
return View(initialData);
}
ビューでは、BeginCollectionItem Html ヘルパーのおかげで、コレクションに新しい項目を動的に追加できます。
これは私の見解です:
@model IEnumerable<DemoWebShop.Controllers.Gift>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorRows").append(html); }
});
return false;
});
}); // end document.ready function
</script>
<h2>Gift List</h2>
What do you want for your birthday?
@using (Html.BeginForm())
{
<div class="form-horizontal">
<div id="editorRows">
@foreach (var item in Model)
{
Html.RenderPartial("GiftEditorRow", item);
}
</div>
@Html.ActionLink("Add another...", "BlankEditorRow", null, new { id = "addItem" })
<input type="submit" value="Finished" />
@*<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Aanmaken" class="btn btn-default" />
</div>
</div>*@
</div>
}
これは "GiftEditorRow" と呼ばれる部分的なビューです:
@using HtmlHelpers.BeginCollectionItem
@model DemoWebShop.Controllers.Gift
@{
Layout = null;
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="editorRow">
@using (Html.BeginCollectionItem("gifts"))
{
<label>Name: </label>
@Html.TextBoxFor(x => x.Name);
<label>Price: </label>
@Html.TextBoxFor(x => x.Price, new { size = 4 });
<br />
}
</div>
}
コントローラー内には、次のアクションメソッドもあります。
public ViewResult BlankEditorRow()
{
return View("GiftEditorRow", new Gift());
}
コレクション内に既に存在する最初のアイテムのみが、コントローラーの HTTP Post メソッドに渡されます。