locked
Multiple Viewmodel addition and validation problem RRS feed

  • Question

  • User-118859203 posted

    Hi guys,

    I need to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.

    public class LoginViewModel

    {

    public string Email { get; set; }

    public string Password { get; set; }

    }

     

    public class RegisterViewModel

    {

    public string Name { get; set; }

    public string Email { get; set; }

    public string Password { get; set; }

    }

    Should I use another ViewModel which holds these 2 ViewModels?

     

    public AdditionalViewModel

    {

    public LoginViewModel LoginViewModel{get; set;}

    public RegisterViewModel RegisterViewModel {get; set;}

    }

    I need the validation attributes to be brought forward to the view, this is why I need the ViewModels.

    Thanks for your help!

    Sunday, January 13, 2019 4:32 AM

Answers

  • User-552477072 posted

    Hi,

    Use a view model that contains multiple view models:

    namespace Project.Web.ViewModels
    {
    public class UserViewModel
    {
    public UserTT User { get; set; }
    public ProductTT Product { get; set; }
    public AddressTT Address { get; set; }
    }
    }
    In your view then you can access as:

    @model MyProject.Web.ViewModels.UserViewModel

    @Html.LabelFor(model => model.User.UserName)
    @Html.LabelFor(model => model.Product.ProductName)
    @Html.LabelFor(model => model.Address.StreetName)

    Hopefully, validation will no more problem as well. 

    Please mark as answer if it helps you. Thanks!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 13, 2019 4:42 AM