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..
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With