Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.TextBoxFor NullReferenceException using Razor syntax

I have a very simple page (I've reduced it to almost nothing to see if I could get this working). A NullReferenceException is being thrown when calling Html.TextBoxFor with the lambda shown below. I am trying to work out why this is?

The exception itself seems to be handled as it doesn't stop rendering the page, but I don't think it should be occurring at all? The text box is actually rendered correct as expected (with the regex and placeholder).

If I swap TextBoxFor for PasswordFor a NullReferenceException is also not thrown.

View:

@model Analytics.Sites.Frontend.Models.RegisterViewModel
<div>
    @using (Html.BeginForm("Register", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "centeralign", role = "form" }))
    {
        @Html.TextBoxFor(m => m.Email, new { @placeholder = "[email protected]" })
    }

</div>

ViewModel

public class RegisterViewModel
{
    [Required]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    [RegularExpression(@"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", ErrorMessage = "The email address you entered is not valid.")]
    public string Email { get; set; }
}

Exception:

System.NullReferenceException
   at lambda_method(Closure , RegisterViewModel )

Ideas? Is this by design and it's throwing and catching an NullReferenceException internally?

Edit:

The controller itself is empty.

[Authorize]
public class AccountController : Controller
{
   [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }
}

Obviously that is not passing a model instance to the view. Changing to return View(new RegisterViewModel) will negate the NRE. Is that the intended way of doing this? The samples show otherwise.

If you create a new skeleton MVC project with VS2013 it has the same code as this on the Account/Register method. The skeleton project also throws (an handles?) the same NRE. Possible this is by design?

like image 668
AndySavage Avatar asked Mar 31 '14 15:03

AndySavage


2 Answers

You must pass an instance of your model to the view:

 public ActionResult Register()
 {
      return View(new RegisterViewModel());
 }

This is the correct practice in MVC. You cannot access a property on a model without an instance of the model.

like image 120
Robert Avatar answered Oct 10 '22 22:10

Robert


If your view is rendering and binding to the model then you need to pass a model to the view. If it's the initial GET of the view you should pass an empty model.

like image 1
Craig W. Avatar answered Oct 10 '22 21:10

Craig W.