Best way to support multiple forms in mvc3 with validation annotiation

主宰稳场 提交于 2019-12-06 09:41:15

The way I approach this problem; where you need 2 or more ViewModels binding to your view, is to create a encompasing ViewModel with 2 properties, then assign the individual login and register models to each property. e.g. (minus any validation you wish to add)

public class LogOnViewModel {
    public string UserName { get; set; }
    public string Password { get; set; }
}

public class RegisterViewModel {
    public string UserName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string ConfirmPassword { get; set; }
}

public class WelcomeScreenViewModel {
    public LogOnViewModel LogOnModel { get; set; }
    public RegisterViewModel RegisterModel { get; set; }
}

In my Welcome view I would have @model namespace.WelcomeScreenViewModel at the top together with 2 partial views pointing to _LogOn and _Register like this:

@Html.Partial("_LogOn", Model.LogOnModel)
@Html.Partial("_Register", Model.RegisterModel)

That way your partial views are passed the correct models and are also re-usable as partial view else where in your web app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!