Answer the question
In order to leave comments, you need to log in
How to bind dynamically created form elements to a Dictionary?
Good day!
There is an ASP.NET MVC 5 project. There is a ViewModel that contains:
public Dictionary<string, string> AdditionalFields { get; set; }
function AddRow() {
var table = document.getElementById("formTable");
var fieldName = prompt("Enter field name", "Field name");
if (fieldName == null) return;
var row = table.insertRow(-1);
var name = row.insertCell(0);
var describtion = row.insertCell(1);
var action = row.insertCell(2);
name.innerHTML = "<label>" + fieldName + "</label>";
describtion.innerHTML = "<input class=\"form-control\" type=\"text\" name=\"" + fieldName + "\" />";
action.innerHTML = "<a href=\"#\" onclick=\"DeleteRow(this)\">Delete</a>";
}
function DeleteRow(element) {
var rowId = element.parentNode.parentNode.rowIndex;
var table = document.getElementById("formTable");
table.deleteRow(rowId);
}
Answer the question
In order to leave comments, you need to log in
In this scenario, no way. Please note that the razor markup in the view is performed on the server side, it executes while rendering the html markup based on the cshtml code, and the js code is executed on the client side and it does not know anything about your dictionary.
I see that as a solution, display your table as a partial view and each time you add / delete a row, make a request to the server with new line parameters and it will return a new table, and, accordingly, the dictionary will be updated.
The second option, when adding a line, make an Ajax request to the server with new parameters for the dictionary, and a partial view will be returned, where there will be code, like this
@model Dictionary<string, string> AdditionalFields
<script>
var additionalFields = [];
@foreach(var field in AdditionalFields)
{
@:additionalFields.push({ '@field.Key', '@field.Value' })
}
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question