Reputation: 751
I am writing a registration page that has both options to register and log in. I would like for these views and models to remain separate, so I am using partial views. However, I am getting a null reference exception when the second partial view attempts to initialize its model. Help would be appreciated.
The null reference exceptions occurs at
@Html.Partial("Login",Model.Login)
RegisterModel
public class RegisterModel
{
public LoginModel Login { get; set; }
public RegisterModel()
{
Login = new LoginModel();
}
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
LoginModel
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
Login.cshtml
@model MvcApplication1.Models.LoginModel
@{
ViewBag.Title = "Log in";
}
<hgroup class="title">
<h1>@ViewBag.Title.</h1>
</hgroup>
<section id="loginForm">
@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Log in Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</li>
<li>
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
</li>
</ol>
<input type="submit" value="Log in" />
</fieldset>
}
</section>
@*<section class="social" id="socialLoginForm">
<h2>Use another service to log in.</h2>
@Html.Action("ExternalLoginsList", new { ReturnUrl = ViewBag.ReturnUrl })
</section>*@
And Register.cshtml (the index)
@model MvcApplication1.Models.RegisterModel
@{
ViewBag.Title = "stuff";
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<div class="register">
<div class="registration_contents">
@Html.Partial("RegisterForm")
</div>
<div class="login_contents">
@Html.Partial("Login",Model.Login)
</div>
</div>
</div>
</section>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Upvotes: 0
Views: 1303
Reputation: 4379
Good afternoon, it looks like in your get request for the Register view you are more than likely not directly instantiating your RegisterModel so when you pass Model.Login to your partial call it is null.
Upvotes: 2