V
V
Vadim2018-06-20 12:53:38
JavaScript
Vadim, 2018-06-20 12:53:38

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; }

The view contains a table whose rows can be added or removed by clicking on the appropriate buttons. Adding and removing lines is done by JS functions:
JavaScript code
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);
    }

Each new table row contains a Label(Key) and a TextBox(Value) that I would like to associate with a dictionary in my model. It seems like you can create a model and pass it to the view from the controller, but then the dictionary will be empty ... How can I bind new input fields with an empty dictionary so that it is automatically filled when a new table row is added?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2018-06-20
@kttotto

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 question

Ask a Question

731 491 924 answers to any question