简体   繁体   English

你调用的对象是空的

[英]Object reference not set to an instance of an object

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 . 我有错误: Object reference not set to an instance of an object How correctly convert 如何正确转换

ViewData["numOfGroups"] to int ? ViewData["numOfGroups"]int

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. 完成此操作后,您将不再获得NullReferenceException并且您的代码应该可以正常工作。

Of course as I've already written it multiple times here you should prefer strongly typed view instead of ViewData . 当然,因为我已经多次在这里写过,你应该更喜欢强类型视图而不是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. 视图不是用于声明变量和编写C#代码。 They are markup. 它们是标记。

If the error was related to converting ViewData["numOfGroups"] to int then you would get FormatException . 如果错误与将ViewData["numOfGroups"]转换为int有关,那么您将获得FormatException Check that you are really passing data to the view and that it contains numOfGroups key. 检查您是否确实将数据传递给视图,并且它包含numOfGroups键。

Seems ViewData["numOfGroups"] is null. 似乎ViewData["numOfGroups"]为空。 It is quite possible that problem is not in conversion itself but in ViewData["numOfGroups"].ToString() . 问题很可能不在于转换本身,而在于ViewData["numOfGroups"].ToString()

Since ViewData dictionary contains <string, object> you have to do unboxing on the value: 由于ViewData字典包含<string, object>您必须对值进行拆箱:

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. 但是,如果转换无法正常工作,请检查对象是否为空,或者通过try / catch进行环绕... ...或者如果转换成功,则使用返回bool的TryParse()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM