【问题标题】:Object reference not set to an instance of an object in Html.Partial MVC when load data加载数据时未将对象引用设置为 Html.Partial MVC 中的对象实例
【发布时间】:2014-02-19 06:12:27
【问题描述】:

我在 mvc 项目中有 _layout.cshtml 页面,该页面使用此代码调用局部视图

@Html.Partial("_MenuForAdmin")

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; }

    }
}

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;
        }

    }
}

部分视图代码_MenuForAdmin.cshtml

@model i_insurance.Models.MenuModel

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

主文件夹中 Index.cshtml 的代码

@{
    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>

当我在浏览器中运行这个项目时,它显示“对象引用未设置为对象的实例”,这是

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

行:3

堆栈跟踪

[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

我的问题是为什么会这样?以及如何解决?

【问题讨论】:

  • 您确定命名空间对您的模型正确吗?
  • 是的,我确定,这在 Visual Studio 编辑器中没有错误。
  • index.cshtml 长什么样子?
  • 欢迎来到 Stack Overflow!几乎所有NullReferenceException 的情况都是一样的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
  • 我没有收到任何错误......我使用了这个代码......

标签: c# asp.net-mvc razor nullreferenceexception


【解决方案1】:

这里是工作代码 -

型号 -

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

}

控制器 -

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;
    }
}

菜单索引新部分视图 -

@model i_insurance.Models.MenuModel

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

然后在您的主索引视图中 -

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

最终输出 -

【讨论】:

  • 是的,伙计。非常感谢您。我认为它与控制器中的返回值有关 return PartialView("_MenuForAdmin",model);
【解决方案2】:

您应该在 index.cshtml 视图中设置 partial 的模型,而不是在布局文件中使用 partial:

@Html.Partial("_MenuForAdmin", Model)

【讨论】:

  • pass 模型不需要这个。
  • @Hakan:我已经尝试在最后一个位置代码中将部分视图移动到 index.cshtml > @Html.Partial("_MenuForAdmin",i_insurance.Models.MenuModel) 但它在 vs 编辑器中显示错误'i_insurance.Models.MenuModel' 是一个'类型',在给定的上下文中无效,所以我尝试在没有模型的情况下通过,但仍然有错误对象未引用,我为此包含了堆栈跟踪。
  • 您应该将@model i_insurance.Models.MenuModel 添加到index.cshtml 的顶部,然后使用@Html.Partial("_MenuForAdmin", Model) 甚至@Html.Partial("_MenuForAdmin")因为您的部分将继承您的视图模型。
  • 好的,不知道可能是什么问题。我现在看到您在部分中缺少@。应该是:@foreach (var item in Model.li) { &lt;text&gt; @item &lt;/text&gt; }
猜你喜欢
  • 2013-07-26
  • 2021-09-14
  • 2020-04-13
  • 2013-03-21
  • 2015-09-27
  • 2014-10-15
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多