tags:

views:

132

answers:

5

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?

A: 

Seems ViewData["numOfGroups"] is null. It is quite possible that problem is not in conversion itself but in ViewData["numOfGroups"].ToString().

Incognito
+1  A: 

If the error was related to converting ViewData["numOfGroups"] to int then you would get FormatException. Check that you are really passing data to the view and that it contains numOfGroups key.

Giorgi
+5  A: 

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.

Darin Dimitrov
+1  A: 

In you view:

int numOfGroups;
int.TryParse(ViewData["numOfGroups"], out numOfGroups);

now you can use numOfGroups as you wish. If it couldn't parse it, it will be 0.

If it should always be able to parse you can throw an exception or log it or something in an if statement since int.TryParse returns a bool. e.g.

int numOfGroups;
if(!int.TryParse(ViewData["numOfGroups"], out numOfGroups))
{
    //log this badness or whatever
}
BritishDeveloper
I can't possibly imagine doing this in a view.
Darin Dimitrov
Then do it properly by putting this NumOfGroups in a view model as a strongly typed int
BritishDeveloper
A: 

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

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

but check if the object is null first or surround by try/catch if there's any chance the conversion will not work... ...or use TryParse() that returns bool if the conversion succeeded or not.

bojanskr
your code will not compile I guess you meant (int)ViewData["numOfGroups"] which however will still be a null ref exception. The most plausible null ref exception in the code OP posted is that ViewData["NoOfGRoups"] is null.
Rune FS
edited, thanks for the observation....
bojanskr