MVC Dynamic Form Fields

I have read this article which shows how to display dynamic fields via the use of editor templates http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

How can I create new fields by clicking an "Add Field" button?

I have googled this and looked at some examples but they seem way too complex for what should be a simple process. In PHP, you would simply append [] to the end of the field name and you could then run it through a loop...

There should be an even simpler way to do this in MVC since it's newer tech, right?

Answers


Dynamic form fields can be accomplished as easy as follows:

Model:

public class MyViewModel
{
    public string Name { get; set; }
    public List<string> EmailAddresses { get; set; }
}

View:

@model MyViewModel

@Html.TextboxFor(m => m.Name)

@* you can add as many of these as you like, or add them via javascript *@
<input type="text" name="EmailAddresses" />
<input type="text" name="EmailAddresses" />
<input type="text" name="EmailAddresses" />
@* you can also use razor syntax *@
@Html.Textbox("EmailAddresses")

Controller:

[HttpPost]
public ActionResult MyAction(MyViewModel model)
{
    // note that model.EmailAddresses contains your list of email addresses
    foreach (string email in model.EmailAddresses)
        email = email; // do whatever you want with this...

    return View();
}

Need Your Help