asp.net-mvc mvc 视图中的模型空引用异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15699777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:42:34  来源:igfitidea点击:

Model Null reference exception in mvc view

asp.net-mvcasp.net-mvc-4

提问by user2189168

The problem is getting null reference exception when passing data from controller to view

问题是在将数据从控制器传递到视图时获取空引用异常

I am Passing a model to the view from the controller like this:

我正在将模型从控制器传递给视图,如下所示:

 {
    ViewBag.PartId = id;
    var viewmodel= new Orderviewmodelnew();
    var order = new OrderMnagernew().GetSingleOrderField(id);
    viewmodel.ProjectId=order.ProjectId;
    return View(viewmodel);
 }

And in the View I have code like this

在视图中我有这样的代码

 @model DreamTrade.Web.BL.ViewModels.OrderViewModelnew


 Home>Project @Model.ProjectID==null??//projected is of type guid

 Customer :@(Model.CreatedBy??string.empty)

 Project :@Model.ProjectID
     @Model.ProjectDetail

  CreatedBy:@Model.CreatedBy

  Creation Date:@Model.CreationDate

 CompletedBy :@Model.ModifiedBy
 Completion Date:@Model.LastModified

 @Model.Image

   @Html.Action("OrderIndex", "Ordernew", new { PartId = Guid.Parse("C0497A40-2ADE-4B23-BA9F-1694F087C3D0") })

I have Tried like this

我试过这样

@if(Model.ProjectId==Null)
 {/....}

In the controller i tried like this by not passing model if it is null

在控制器中,如果模型为空,我尝试通过不传递模型

 var order = new OrderMnagernew().GetSingleOrderField(id);
    if(order!=null)
   {
        viewmodel.ProjectId=order.ProjectId;
        return View(viewmodel);

   }
 return View()

The problem with this the projectid in the view is showing exception.

视图中的 projectid 的问题是显示异常。

I Want to display empty string if it is null and show the remaining part..

如果它为空,我想显示空字符串并显示其余部分..

采纳答案by webdeveloper

This code is wrong:

这段代码是错误的:

@Model.ProjectID==null??string.empty

if ProjectIDis nullable type, you should write:

如果ProjectID是可空类型,你应该写:

@(Model.ProjectID ?? string.empty)

Added:

添加:

Replace:

代替:

return View()

with:

和:

return View(new Orderviewmodelnew())

because nullobject doesn't have any properties

因为null对象没有任何属性

回答by Nicholas Butler

By putting

通过把

@model DreamTrade.Web.DALNew.Source

at the top of your view, you're making a strongly-typed view which expects a model of that type.

在视图的顶部,您正在创建一个强类型视图,该视图需要该类型的模型。

However, in your controller, you're passing a model of type Orderviewmodel

但是,在您的控制器中,您正在传递一个类型的模型 Orderviewmodel

You need to make sure the model you pass to the view is of the right type.

您需要确保传递给视图的模型是正确的类型。