Saturday, 24 February 2018

c# - Object Reference not set to an object (calling Razor model from View)




Using C# MVC4



My View:



@using Universe.Models
@model UserModel
@section css {
}
@using (Html.BeginForm("AddUser","Home", FormMethod.Post))
{










My Model:



public class UserModel
{
public int Id { get; set; }
public string Alias { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public bool IsExternal { get; set; }


public UserModel()
{

}

public UserModel(User user)
{
if (user == null) return;
Alias = user.Alias;
}
}


But, I keep getting the error:



enter image description here



When I try to debug it, it doesn't even go into the Html.TextBox method or into my model.


Answer



Without seeing your controller action, my guess would be that your model is null.



In your controller, make sure you are passing an instance of the model to your view. For example:



return View(new UserModel());


Instead of:



return View();

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...


Alias:

@Html.TextBox(Model.Alias)


Blog Archive