Created
May 24, 2018 15:44
-
-
Save OdeToCode/86c53b3cd1dc82a3aa0429d0019cf48d to your computer and use it in GitHub Desktop.
ASP.NET Core Binding Collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@using WebApp1.Controllers | |
@model IList<Widget> | |
@{ | |
ViewData["Title"] = "ShowEditWidgets"; | |
Layout = null; | |
} | |
<h2>Dump of Widgets</h2> | |
<table> | |
@foreach(var widget in Model) | |
{ | |
<tr> | |
<td>@widget.Description</td> | |
<td>@widget.Area.Number</td> | |
</tr> | |
} | |
</table> | |
<h2>Edit Widgets</h2> | |
<form method="post"> | |
@for(var i = 0; i < Model.Count; i++) | |
{ | |
<div> | |
<input asp-for="@Model[i].Description" /> | |
<input asp-for="@Model[i].Area.Number" /> | |
</div> | |
<hr /> | |
} | |
<input type="Submit" value="Save" /> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Area | |
{ | |
public int Number { get; set; } | |
} | |
public class Widget | |
{ | |
public string Description { get; set; } | |
public Area Area { get; set; } | |
} | |
public class TestController : Controller | |
{ | |
public IActionResult Index(IEnumerable<Widget> widgets) | |
{ | |
List<Widget> model; | |
if (widgets.Count() < 1) | |
{ | |
model = new List<Widget> | |
{ | |
new Widget { Description="Widget1", Area = new Area { Number = 10 }}, | |
new Widget { Description="Widget2", Area = new Area { Number = 11 }}, | |
new Widget { Description="Widget3", Area = new Area { Number = 12 }}, | |
new Widget { Description="Widget4", Area = new Area { Number = 13 }} | |
}; | |
} | |
else | |
{ | |
// note: could also accept parameter of type List<Widget> to avoid this, | |
// but the view will need a type with an indexer | |
model = widgets.ToList(); | |
} | |
return View("ShowEditWidgets", model); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment