Skip to content

Instantly share code, notes, and snippets.

@SupernaviX
Last active January 4, 2016 13:49
Show Gist options
  • Save SupernaviX/8630528 to your computer and use it in GitHub Desktop.
Save SupernaviX/8630528 to your computer and use it in GitHub Desktop.
Nested Collection Postback with ASP.NET MVC Framework
@model CollectionPostback.Models.Building
@using (Html.BeginForm("Post", "Home"))
{
<fieldset>
<legend>Building</legend>
@Html.TextBoxFor(m => m.Name)
<ul class="collection" data-name="Floors">
@foreach (var floor in Model.Floors)
{
@Html.Partial("Floor", floor)
}
</ul>
</fieldset>
<input type="submit" />
}
<script>
$("form").submit(function () {
$(".collection").each(function (index, element) {
var collection = $(element);
collection
.attr("data-name", function(i, oldVal) {
var closest = collection.closest(".collection-item").attr("data-name");
return (closest ? closest + "." : "") + oldVal;
})
.find(".collection-item:not([data-name])").not(".collection-item:not([data-name]) .collection-item:not([data-name])")
.attr("data-name", function (i) {
return collection.attr("data-name") + "[" + i + "]";
});
});
$(".collection-item input").each(function (index, element) {
var colItem = $(element);
var colItemName = colItem.closest(".collection-item").attr("data-name") + "." + colItem.attr("Name");
colItem
.attr("Name", colItemName)
.attr("Id", colItemName.replace(/[\[.\]]/g, "_"));
});
});
</script>
@model CollectionPostback.Models.Floor
<li class="collection-item">
<fieldset>
<legend>Floor</legend>
@Html.EditorFor(m => m.Order)
<ul class="collection" data-name="Spaces">
@foreach (var space in Model.Spaces)
{
@Html.Partial("Space", space)
}
</ul>
</fieldset>
</li>
@model CollectionPostback.Models.Space
<li class="collection-item">
<fieldset>
<legend>Space</legend>
@Html.TextBoxFor(m => m.Name)
</fieldset>
</li>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment