How can i bind dynamic created form data of my view to my underlying model?
As a small example here my Model/Controller:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; namespace temp.Pages { public class AboutModel : PageModel { [BindProperty] public Dictionary<string, string> dict { get; set; } public AboutModel() { dict = new Dictionary<string, string>(); dict.Add("Key1", "Value1"); dict.Add("Key2", "Value2"); dict.Add("Key3", "Value3"); dict.Add("Key4", "Value4"); } } }
And here my view:
@page "{handler?}" @model AboutModel @{ ViewData["Title"] = "About"; }<h2>@ViewData["Title"]</h2><p>Use this area to provide additional information.</p><br /> <br /><form method="post"><div id="temp"> @foreach(var kvp in Model.dict) {<input asp-for="@kvp.Key" /><input asp-for="@kvp.Value" /><br /> }</div> <br /><br /><input type="button" value="Add a field" class="add" id="add" /><input type="submit" value="Submit"></form> @section Scripts { <script>$(function(){$('#add').on('click',function(){ var r= $('<input /><input /><br />');$("#temp").append(r); }); });</script> }
So when i run my application i will se my Dictionary entries inside my view, which is correct. But then i want the user to let add new input in which he can enter some data. Then onPost() the entered data should be binded to the whole Dictionary, as it would be done with simple strings like for example @Model.FirstName for which i have the public string FirtName {get; set;} inside my model, so that the old data and the new data (all the data of the Dictionary) is still shown on the page after POST.
So how can i do this? Please take care of it that i'm using .Net Core 2 with Razor Pages. So i want to know a nice and smooth working solution for this "setup".