0

我已经创建了一个具有两个部分视图登录和注册的视图页面。对于这两者,我为两者创建了视图模型和组合模型,如下所示。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace ProjectHub.ViewModels
{
    public class LoginModel
    {
         public string Username { get; set; }
         public string Password { get; set; }
    }
    public class RegisterModel
    {
         public string FullName { get; set; }
         public string Email { get; set; }
         //Some properties as well
    }
    public class LoginOrRegisterModel
    {
         public LoginModel Loginmodel { get; set; }
         public RegisterModel Registermodel { get; set; }
    }
}

Index.cshtml @model ProjectHub.ViewModels.LoginOrRegisterModel

 @Html.Partial("_Register", Model.Registermodel) 
 @Html.Partial("_Login",Model.Loginmodel)

_Login.cshtml

  @model ProjectHub.ViewModels.LoginModel

  @using (Html.BeginForm("Login", "account", FormMethod.Post))
  {
    @Html.ValidationSummary(true)
    <div class="label">@Html.Label("Username")</div>
    <div class="field">@Html.TextBoxFor(m => m.Username)</div>

    <div class="label">@Html.Label("Password")</div>
    <div class="field">@Html.PasswordFor(m => m.Password)</div>

    <input class="field" id="submit" type="submit" value="Login" />
}

_Register.cshtml

 @model ProjectHub.ViewModels.RegisterModel

 @using (Html.BeginForm("Register", "account", FormMethod.Post))
 {
    <div class="label">@Html.Label("Name")</div>
    <div class="field">@Html.TextBoxFor(m => m.FullName)</div>

    //Some other labels and fields

    <input class="field" id="submit" type="submit" value="Sign Up" />
    @Html.ValidationSummary()   
}

 public ActionResult Index()
    {
        return View();
    }

现在,当我尝试运行应用程序时,出现错误“对象引用未设置为对象的实例”。在 @Html.Partial("_Register", Model.Registermodel) 和 @Html.Partial("_Login",Model.Loginmodel) 处的 Index.cshtml 中。请帮我。

4

1 回答 1

2

看起来该Model属性在呈现这些部分的主视图中为空。确保在呈现此主视图的控制器操作中,您已正确初始化并将其传递LoginOrRegisterModel给视图:

public ActionResult SomeAction()
{
    LoginOrRegisterModel model = new LoginOrRegisterModel();
    model.Loginmodel = new LoginModel();
    model.Registermodel = new RegisterModel();
    return View(model);
}
于 2013-02-23T17:08:09.767 回答