...">

Object reference not set to an instance of an object

In this line of code

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

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

ViewData["numOfGroups"]before int?

+3
source share
4 answers

First you need to make sure your controller action sets this variable:

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

Once you do this, you will no longer receive NullReferenceException, and your code should work.

Of course, since I wrote this several times here, you should prefer a strongly typed view instead ViewData. You must also enter model properties accordingly. You should not parse lines for consideration. So:

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

And in your opinion:

<% var tmp = Model.NumOfGroups; %>

, , , , , . #. .

+5

ViewData["numOfGroups"] int, FormatException. , numOfGroups.

+1

, ViewData["numOfGroups"] null. , , ViewData["numOfGroups"].ToString().

0

Since the ViewData dictionary contains <string, object>, you need to do unboxing for the value:

int tmp = (int)ViewData["numOfGroups"];

but check if the object is first zero or surrounding with try / catch if there is a chance the conversion will not work ... ... or use TryParse()that returns bool if the conversion is successful or not.

0
source

Source: https://habr.com/ru/post/1756707/


All Articles