12

Using C# MVC4

My View:

@using Universe.Models
@model UserModel
@section css {
<link href="@Url.Content("~/Content/assets/charcreation.css")" rel="stylesheet"/>}
@using (Html.BeginForm("AddUser","Home", FormMethod.Post))
{

<div class="row-fluid">
            <table id="tblBio">
                <tr>
                    <td class="span3">
                        <span class="labeltext">Alias:</span>
                    </td>
                    <td class="span5">
                        @Html.TextBox(Model.Alias)
                    </td>
                    <td class="span4">
                        <span class="ui-state-highlight hidden"></span>
                    </td>
                </tr>

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.

ataravati
  • 8,891
  • 9
  • 57
  • 89
ArjaaAine
  • 886
  • 5
  • 14
  • 27
  • 2
    For kicks, can you show your Controller Action..where you call the view? – ltiong_sh Aug 24 '13 at 01:02
  • Well, maybe it's just really not set to an instance of object? Have you checked if Alias isn't null? – VsMaX Aug 24 '13 at 01:26
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Aug 24 '13 at 01:43
  • I am sorry guys, I am new to MVC.. but based on the responses below.. it was my controller class, I was not passing my Model. I thought controller classes were only invoked on Posts. – ArjaaAine Aug 24 '13 at 17:40

2 Answers2

30

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();
htxryan
  • 2,871
  • 2
  • 21
  • 21
5

You have to pass your Model in your Controller Action when return the specific View

return View(new Model());
Imad Alazani
  • 6,688
  • 7
  • 36
  • 58
imsurya
  • 154
  • 1
  • 6