0

在我的 asp.net mvc4 应用程序中,我希望允许用户在注册期间将多个地区和城市添加到他们的帐户中。我想添加一些子表单,其中将是地区和城市的下拉列表,用户应该能够在注册过程中添加多个地区和城市。我知道如何使用 jquery 执行此操作,但我想使用视图模型进行验证和创建此注册表单,但我不知道如何创建此视图模型以及如何在视图中定义此表单。我正在说明我当前的注册视图模型,我想问您是否可以帮助我修改它,以便它可以按我的需要工作。

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; }

}

谢谢你。

4

1 回答 1

2

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.

于 2013-09-15T14:05:11.133 回答