Multiple models in a view

前端 未结 12 1830
太阳男子
太阳男子 2020-11-21 23:07

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

e.g.

pub         


        
12条回答
  •  太阳男子
    2020-11-21 23:24

    I'd recommend using Html.RenderAction and PartialViewResults to accomplish this; it will allow you to display the same data, but each partial view would still have a single view model and removes the need for a BigViewModel

    So your view contain something like the following:

    @Html.RenderAction("Login")
    @Html.RenderAction("Register")
    

    Where Login & Register are both actions in your controller defined like the following:

    public PartialViewResult Login( )
    {
        return PartialView( "Login", new LoginViewModel() );
    }
    
    public PartialViewResult Register( )
    {
        return PartialView( "Register", new RegisterViewModel() );
    }
    

    The Login & Register would then be user controls residing in either the current View folder, or in the Shared folder and would like something like this:

    /Views/Shared/Login.cshtml: (or /Views/MyView/Login.cshtml)

    @model LoginViewModel
    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
    {
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
    }
    

    /Views/Shared/Register.cshtml: (or /Views/MyView/Register.cshtml)

    @model ViewModel.RegisterViewModel
    @using (Html.BeginForm("Login", "Auth", FormMethod.Post))
    {
        @Html.TextBoxFor(model => model.Name)
        @Html.TextBoxFor(model => model.Email)
        @Html.PasswordFor(model => model.Password)
    }
    

    And there you have a single controller action, view and view file for each action with each totally distinct and not reliant upon one another for anything.

提交回复
热议问题