0

I have _layout.cshtml page in mvc project that call partial view with this code

@Html.Partial("_MenuForAdmin")

The code for MenuModel :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace i_insurance.Models
{
    public class MenuModel
    {
        public List<string> li { get; set; }

    }
}

The code for MenuController :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using i_insurance.Models;
using i_insurance.DataAccess;
using System.Data;

namespace i_insurance.Controllers
{
    public class MenuController : Controller
    {

        public ActionResult Index()
        {
            MenuModel model = new MenuModel();
            model.li = LoadUl();
            return View(model);
        }

        public List<string> LoadUl()
        {
            List<string> list = new List<string>();
            list.Add("Testing");
            list.Add("MCV");
            list.Add("Project");
            return list;
        }

    }
}

The code for partial view _MenuForAdmin.cshtml :

@model i_insurance.Models.MenuModel

@foreach (var item in Model.li) {
<text>
    item
</text> }

The code for Index.cshtml inside home folder :

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>
                <h2>@ViewBag.Message</h2>
            </hgroup>

        </div>
    </section>
}
<h3>We suggest the following:</h3>
<ol class="round">
    <li class="one">
        <h5>Getting Started</h5>
        ASP.NET MVC gives you a powerful
    </li>
</ol>

and when i run this project in browser it show "Object reference not set to an instance of an object" , here is the

Source Error:

Line 1:  @model i_insurance.Models.MenuModel
Line 2:  
Line 3:  @foreach (var item in Model.li)
Line 4:  {
Line 5:      <text>

Source File: d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\Shared\_MenuForAdmin.cshtml

Line: 3

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   ASP._Page_Views_Shared__MenuForAdmin_cshtml.Execute() in d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\Shared\_MenuForAdmin.cshtml:3
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +88
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection) +277
   System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData) +91
   System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName) +32
   ASP._Page_Views_Home_Index_cshtml.Execute() in d:\Projects\VS2012\Website\i_insurance\i_insurance\Views\Home\Index.cshtml:24
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +22
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +75
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9634212
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

my question is why this happen ? and how to solve it ?

Deddy H
  • 252
  • 2
  • 6
  • 19

2 Answers2

2

Here goes working code -

Model -

public class MenuModel
{
    public List<string> li { get; set; }

}

Controller -

public class MenuController : Controller
{
    public ActionResult IndexNew()
    {
        MenuModel model = new MenuModel();
        model.li = LoadUl();

        return PartialView("_MenuForAdmin",model);
    }

    public List<string> LoadUl()
    {
        List<string> list = new List<string>();
        list.Add("Testing");
        list.Add("MCV");
        list.Add("Project");
        return list;
    }
}

Menu IndexNew Partial View -

@model i_insurance.Models.MenuModel

@foreach (var item in Model.li)
{
    <text>
        @item
    </text> 
}

And then in your Main Index View -

@{
    Html.RenderAction("IndexNew", "Menu");
}

Finally Output -

enter image description here

ramiramilu
  • 17,044
  • 6
  • 49
  • 66
  • yes, it work mate. thank you very much. i thing it related with the return value in controller return PartialView("_MenuForAdmin",model); – Deddy H Jan 28 '14 at 06:48
0

You should set the model of the partial in your index.cshtml view, and not using the partial in the layout file:

@Html.Partial("_MenuForAdmin", Model)
Håkan Fahlstedt
  • 2,040
  • 13
  • 17
  • this is not necessary for pass model. – Jeet Bhatt Jan 28 '14 at 05:38
  • @Hakan : i already tried to move partial view to index.cshtml in the last position code > @Html.Partial("_MenuForAdmin",i_insurance.Models.MenuModel) but it show error in vs editor 'i_insurance.Models.MenuModel' is a 'type', which is not valid in the given context so i tried pass without model, but still have error object not reference, i include the stacktrace for that. – Deddy H Jan 28 '14 at 06:03
  • You should add @model i_insurance.Models.MenuModel to the top of index.cshtml and then use @Html.Partial("_MenuForAdmin", Model) or even @Html.Partial("_MenuForAdmin") as your partial will inherit the model of your view. – Håkan Fahlstedt Jan 28 '14 at 06:06
  • Ok, not sure what could be the problem. I saw now that you are missing an @ in the partial. It should be: `@foreach (var item in Model.li) { @item }` – Håkan Fahlstedt Jan 28 '14 at 06:20