Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference not set to an instance of an object

Tags:

c#

asp.net-mvc

In this line of code

  <% var tmp = int.Parse(ViewData["numOfGroups"].ToString()); %>

I have error:Object reference not set to an instance of an object. How correctly convert

ViewData["numOfGroups"] to int?

like image 573
Ognjen Avatar asked Dec 19 '25 08:12

Ognjen


1 Answers

You should first make sure that your controller action is setting this variable:

public ActionResult Index()
{
    ViewData["numOfGroups"] = "15";
    return View();
}

Once you've done this you should no longer get a NullReferenceException and your code should work.

Of course as I've already written it multiple times here you should prefer strongly typed view instead of ViewData. Also you should type your model properties accordingly. It is not the responsibility of the view to parse strings. So:

public ActionResult Index()
{
    var model = new MyModel
    {
        NumOfGroups = 15
    };
    return View(model);
}

And in your view:

<% var tmp = Model.NumOfGroups; %>

By the way this should also be avoided as I have the feeling that you are declaring variables in your view which means that you have the intent of using them. Views are not for declaring variables and writing C# code. They are markup.

like image 51
Darin Dimitrov Avatar answered Dec 20 '25 20:12

Darin Dimitrov