Question

Is it possible to have a form in MVC 5 where you can add dynamic fields using jQuery as here: JSFiddle

And then post those fields to model using MVC?

In fact my viewmodel where I want to save those values is a List<string> where all those values will be saved.

Was it helpful?

Solution

When dynamically adding the inputs you need to ensure they are named/indexed correctly for postback. For example, if your post action method is

[HttpPost]
public ActionResult Edit(List<string> text)
{
  ...

then your inputs need to be named

<input name="[0].text" value=.../>
<input name="[1].text" value=.../>
<input name="[2].text" value=.../>

so you need to modify the script to create the correct name attribute. Note the indexes need to start at zero and be sequential so you will need to take into account what happens if an input in the middle of the list is removed by the user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top