Multiple models in a view

前端 未结 12 1866
太阳男子
太阳男子 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:44

    There are lots of ways...

    1. with your BigViewModel you do:

      @model BigViewModel    
      @using(Html.BeginForm()) {
          @Html.EditorFor(o => o.LoginViewModel.Email)
          ...
      }
      
    2. you can create 2 additional views

      Login.cshtml

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

      and register.cshtml same thing

      after creation you have to render them in the main view and pass them the viewmodel/viewdata

      so it could be like this:

      @{Html.RenderPartial("login", ViewBag.Login);}
      @{Html.RenderPartial("register", ViewBag.Register);}
      

      or

      @{Html.RenderPartial("login", Model.LoginViewModel)}
      @{Html.RenderPartial("register", Model.RegisterViewModel)}
      
    3. using ajax parts of your web-site become more independent

    4. iframes, but probably this is not the case

提交回复
热议问题