Anton Kandybo
Anton Kandybo

Reputation: 4098

How to dynamically add textbox in the MVC 3

I have two models:

public class Contact
{
    public Guid ContactId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

}

public class Email
{
    public Guid EmailId { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    public string Name { get; set; }

    public Guid ContactId { get; set; }
}

Is it possible with MvcScaffolding, to automatically be generated View Contacts-> Create with dynamic textbox for field email?
For example, when entering the email in the first textbox, then the following created another textbox, etc.

Upvotes: 1

Views: 1868

Answers (1)

mccow002
mccow002

Reputation: 6914

In your model, make the email field a List.

If you set the names as follows, the mvc model binder will automatically populate your list on postback:

<input name="Emails[0]" type="text" />
<input name="Emails[1]" type="text" />
<input name="Emails[2]" type="text" />

and so forth. I'm assuming you're using jquery or something similar to dynamically add the textboxes, so just set the new textboxes name equal to total count - 1. And if you want to allow the user to remove any one of the textboxes, you'll have to go back through and recalculate the names and their index.

Upvotes: 2

Related Questions