Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model Null reference exception in mvc view

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.

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

like image 525
user2189168 Avatar asked Mar 29 '13 08:03

user2189168


People also ask

How do I fix NullReferenceException object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

What is null reference exception in VB net?

The NullReferenceException is designed as a valid runtime condition that can be thrown and caught in normal program flow. It indicates that you are trying to access member fields, or function types, on an object reference that points to null. That means the reference to an Object which is not initialized.

What is System NullReferenceException?

A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.


1 Answers

This code is wrong:

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

if ProjectID is nullable type, you should write:

@(Model.ProjectID ?? string.empty)

Added:

Replace:

return View()

with:

return View(new Orderviewmodelnew())

because null object doesn't have any properties

like image 198
webdeveloper Avatar answered Oct 25 '22 00:10

webdeveloper