ASP.NET MVC Form with Dynamic Fields

Problem

I want to display a form that will have a variable. However, each form element must have a kind of key associated with it. For example, the form generates a name, username and padding fields, I also need to have keys generated in such a way that when the form is submitted, the recipient method can determine what the element is.

Attempt to solve

Now I have a list of FieldItems, where FieldItem is just a class with one String variable. The solution works when filling out the form, however, when presented, the list is returned, and I can not determine which value belongs to which key. I was thinking about using a dictionary, but I don't know how this will be achieved in a razor.

Show model

public class BuildReportViewModel { public IList<BuildReportFieldItemViewModel> Fields { get; set; } } public class BuildReportFieldItemViewModel { public string Field { get; set; } } 

Editor for BuildReportFieldItemViewModel

 @model BuildReportFieldItemViewModel <div class="editor-label"> <label for="@Model.Field">@Model.Field</label> </div> <div class="editor-field"> <input type="text" name="@Model.Field"> </div> 
+4
source share
1 answer

Try using a hidden key field

View Model

 public class BuildReportViewModel { public IList<BuildReportFieldItemViewModel> Fields { get; set; } } public class BuildReportFieldItemViewModel { public string Field; public string Key; } 

Editor for BuildReportFieldItemViewModel

 @model BuildReportFieldItemViewModel <div class="editor-label"> <label for="@Model.Field">@Model.Field</label> </div> <div class="editor-field"> @Html.TextBoxFor(x => x.Field) @Html.Hidden(Model.Key, "key_value"); </div> 
+4
source

Source: https://habr.com/ru/post/1416605/


All Articles