Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am creating a View and calling Partial View in it as below

@{
    //ViewBag.Title = "";
    Layout = "~/Views/Shared/_restLayout.cshtml";
}


<div class="row sidebar_left ">
    <div class="column_center">
        <div id="main_content" class="col-sm-9">
            @RenderBody()
        </div>
    </div>

    <div class="column_left column col-sm-3">
        <div class="widget widget__collections">
            <h3 class="widget_header">Collections</h3>
            @Html.Partial("categoryPartial")
        </div>
    </div>
</div>


When I run the application it throws an error "Object reference not set to an instance of an object " in foreach loop.


@model IEnumerable<fashionHub_new.Models.category>

<div class="widget_content">
    <ul class="list">
        @foreach (var item in ViewData["Category"] as List<fashionHub_new.Models.category>)
        {
            <li class="underwear-socks">
                <a href="#" title="ABC">ABC</a>
            </li>
        }
    </ul>
</div>


Please find my controller below

public ActionResult Index()
        {
            ViewData["Category"] = _businessLayer.ViewAllCategory().ToString();
            return View();
        }


Please provide the solution for the same.
Posted
Comments
Thanks7872 25-Aug-15 5:23am    
At the line you got the error,check which variable is null and make changes such that it should not be null at that point.

1 solution

ViewData["Category"] = _businessLayer.ViewAllCategory().ToString();


ViewData["Category"] is being set to a string.

ViewData["Category"] as List<fashionHub_new.Models.category>)


the "as" tries to convert ViewData["Category"] (a string) as a List<category> and if it can't it returns null. As your ViewData is a string it will return null. You probably need to do this instead in your controller

ViewData["Category"] = _businessLayer.ViewAllCategory().ToList();
 
Share this answer
 
v2
Comments
mayank.bhuvnesh 25-Aug-15 5:58am    
Thnx Buddy.... It worked....:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900