Asp.net mvc4 布局中带有模型的部分 View

标签 asp.net asp.net-mvc asp.net-mvc-4

我正在尝试使用名为 _Menus 的部分 View 在我的 _Layout 页面中创建菜单,该 View 从我的服务器上的 Json 文件读取。但我不知道如何从布局页面调用带有模型的部分 View 。

这是 _Menu.cshtml 页面,位于共享文件夹中:

@model IEnumerable<LangSite_151209.Models.MenuItem>

<div id="menu" class="largescreen_show smallscreen_hide" data-display="flex">
    <div id="menu_left" class="menu_item">

        @foreach (var mainMenuItem in Model)
        {
           // A bunch of stuff with the model that draws the menu
        }
   </div>
</div>

这是我在 _Layout 页面中的调用方式:

<!DOCTYPE html>

<html lang="en">
<head>
     <!-- Meta and script stuff -->
</head>
<body style="overflow:hidden;"> 


    <div id="fg">

        <div id="mobile_wrapper">
        @Html.Partial("../Shared/_Menu")
        </div>

    </div>
    <!-- A bunch of footer stuff that's irrelevant here -->
</html>

我尝试使用 SharedController 返回部分 View ,该 SharedController 打开 Json 文件并将其转换为部分的模型,如下所示:

public class SharedController : Controller
{
    // GET: Shared
    [ChildActionOnly]
    public ActionResult _Menu()
    {
        string filePath = HostingEnvironment.MapPath(@"~/App_Data/MenuItems.json");
        StreamReader sr = new StreamReader(filePath);

        string JsonString = sr.ReadToEnd();
        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All
        };
        var menuItems = JsonConvert.DeserializeObject<List<MenuItem>>(JsonString, settings);

        return View(menuItems.ToList());
    }       
}

但是当我尝试这样做时,我在模型上收到 NullReferenceException:“对象引用未设置为对象的实例。”显然你不能以这种方式将模型传递给部分模型。我知道读取 Json 对象的代码是有效的,因为当我在常规(非部分)页面上使用相同的代码时,它会正确传递模型并且脚本会绘制菜单。

通常,如果我想将模型传递给部分模型,我只需将模型放在主页中并以这种方式传递即可。但我不知道如何将模型放入 _Layout 中。我就应该这样吗?或者有更好的办法吗?

最佳答案

@Html.Partial("../Shared/_Menu") 行不会执行您的 _Menu 操作方法。您的 _Menu.cshtml 部分 View 被强类型化为 MenuItem 列表。所以要么你应该 explicitly pass当调用 Html.Partial 方法或您的主视图(正在调用此部分)时,它也应该输入到同一个集合中。

您应该使用Html.Action方法而不是Html.Partial

@Html.Action("_Menu", "Shared")

这将执行_Menu操作方法并将所需的数据(MenuItem列表)传递给相应的部分 View 。

关于Asp.net mvc4 布局中带有模型的部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36581699/

相关文章:

c# - 无法加载类型 'WebApplication1.SiteMaster'

c# - 是否可以将 ASP.NET 成员资格与在 ASP.NET Identity 2.0 中创建的表一起使用以进行身份​​验证?

asp.net-mvc - 使用 401 : Asp.net Web-api 发送消息

c# - Bootstrap 图片库 + ASP.net C# MVC

asp.net-mvc - 将 powershell 脚本添加到 mvc 站点的 Web 部署包

c# - 尝试在没有模型出现 "tree may not contain dynamic operation"错误的情况下使用 DropDownListFor

c# - MVC4 cshtml页面函数调用

c# - asp.net mvc中写查询的正确位置

javascript - 将map.svg绘制到浏览器并在每个区域单击执行任务

asp.net - 将 MVVM 应用于 ASP.NET