2

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Is this using @Html.BeginCollectionItem ?
No you don't necessarily that - its just a helper that you may find easier to work with. The key to posting back a collection is to name the elements correctly with an indexer
What about if I will have a List<object> where object has 2 properties: Id and value. How the elements should be named?
For example List<Employee> and Employee has properties FirstName and LastName, then the inputs would be <input name="employees[0].FirstName" ... and <input name="employees[0].LastName" ... and postback to public ActionResult Edit(List<Employee> employees)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.