I have some problem in understanding how does the asp.net mvc deal with Null values .
In the first scenario i have the following action method:-
[HttpPost]
public ActionResult Delete(int labtestid, int visitid)
{
try
{
var vlr = repository.GetVisitLabResult(labtestid,visitid);
string desc = vlr.LabTest.Description;
repository.DeleteVisitLabResult(vlr);
repository.Save();
return Json(new { IsSuccess = "True", id = labtestid, description = desc }, JsonRequestBehavior.AllowGet);
}
Incase the repository method var vlr = repository.GetVisitLabResult(labtestid,visitid); does not return any result (var vlr is null) then the following exception will be raised on the string desc = vlr.LabTest.Description; NullReferenceException was unhandled by user code. So why did the framework raise an exception instead of just assigning a null value to the string desc !!!
BR
It looks like the actual object itself is null. You have a null object and you’re trying to access properties on it, hence the runtime will throw a
NullReferenceException. You’re best off checking if the object is null first before trying to access it’s members 🙂