In my asp.net mvc4 app I want to allow users to add multiple regions and cities to their account during the registration. I want to add some subform in which would be the dropdownlist for Region and City and the user should be able to add multiple regions and cities during the registration Process. I know how to do this with jquery but I want to use view model for validation and for creation of this registration form but I do not know how to create this view model and how to define this form in view. I am stating my current registration view model and I want to ask if You can help me to modify it so it will work as I need.
public class RegisterUserModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
public string Password { get; set; }
[DataType(DataType.Password)]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
}
Thank you.
You will need to add a collection to your view model that will contain the Regions and Cities. You should create another type to encapsulate these two properties, say Place, so your View Model will look like this:
public class RegisterUserModel
{
// other properties
public List<Place> Places { get; set; }
}
public class Place
{
public string Region { get; set; }
public string City { get; set; }
}
To display the current places in the View Model you simply iterate over them with a foreach
and use the helpers to display the Region and City for each one. To add a new Place the key is to name the input correctly so the default Model Binder will treat it as an item in the collection. The default Model Binder uses indexes to do this. For example, the inputs for the first Place in the Places collection should be named like this:
<input name="Places[0].Region" />
<input name="Places[0].City />
The next Place in the collection would be [1]
and so on. Since you are familiar with jQuery I will skip how these can be added to the DOM.