Friday, 20 March 2015

MVC NullReference Exception


1. Null Reference Exception :-


Null reference exception occurred at view page because you have not passed the model object from the controller class to
the respective view page

e.g:-
public ActionResult Index()
{
            Customer obj = new Customer();
            obj.id = 1001;
            obj.name = "raju";
            return View("index");//--->this will inoke the view index.aspx
}

[index.aspx]
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcCustomer.Models.Customer>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        The customer id is <%=Model.id %> //-->Model is used to bind view with Model objects
        The customer name is <%=Model.name %>
    </div>
</body>
</html>

//This will cause "NullreferenceExceptoin" error at view page because you have not passed the model object from the
controller to the view page

solution :- Pass the object in the view as follows:-
public ActionResult Index()
{
            Customer obj = new Customer();
            obj.id = 1001;
            obj.name = "raju";
            return View("index",obj);//--->this will invoke the view index.aspx
}


No comments:

Post a Comment