【问题标题】:Render <List> data in partial page in ASP.NET MVC 5在 ASP.NET MVC 5 的部分页面中呈现 <List> 数据
【发布时间】:2014-01-14 14:20:52
【问题描述】:

我需要在部分页面中呈现列表数据...我有存储过程负责获取菜单列表并在视图中有主 Layoutpage--> 共享文件夹--> 现在我在 masterLayout 页面中呈现部分页面但我没有得到任何结果。我知道部分页面不通过控制器,所以我将如何传递数据?

控制器动作

public ActionResult DisplayFunctionsList()
    {
       var myList = F_UOF.GetAllFunctions();

        return View(myList);
    }

存储过程映射(模型)类

  public class GetAllFunction_SP_Map
{
    public GetAllFunction_SP_Map() { }

    [Key]
    public int Hierarchy_ID { get; set; }

    [Required]
    public int ParentID { get; set; }

    [StringLength(250)]
    [Required]
    public string ParentName { get; set; }

    [Required]
    public int ChildID { get; set; }

    [StringLength(250)]
    [Required]
    public string ChildName { get; set; }

    [StringLength(250)]
    [Required]
    public string Controller { get; set; }

    [StringLength(250)]
    [Required]
    public string Action { get; set; }
}

MasterLayout 页面

 @Html.Partial("_DisplayFunctionList_Partial")

部分页面(_DisplayFunctionList_Partial)

@model IEnumerable<DatabaseLayer.StoreProcedures.StoreProceduresMapping.GetAllFunction_SP_Map>

@foreach(var item in Model)
{
  @item.ParentName 
}

【问题讨论】:

  • “部分页面不通过控制器”是什么意思?您可以在控制器操作中使用 return PartialView(view_name, model);
  • 表示通常从控制器在 actionResult 方法中调用 view() 并在 view(model x) 中传递所有数据或模型
  • 您到底想做什么?将对象发送到主布局页面?
  • @toxic,我一直打电话给PartialView() :)
  • 是 PartialView() 在 materPage 布局中工作;位于文件夹> View-->Shared-->MasterLayout

标签: asp.net-mvc razor partial-views


【解决方案1】:

在此示例中,由于您是从母版页调用的,因此您希望使用 Html.RenderAction() 方法。

@{Html.RenderAction("DisplayFunctionsList", "Controller");}

编辑 - Html.RenderAction 必须在函数调用的末尾用分号 (';') 括起来。为避免这种情况,您可以使用 @Html.Action 调用,它返回一个 MvcHtmlString

@Html.Action("DisplayFunctionsList", "Controller")

此外,在使用此方法时,您需要稍微更改视图结果,因为您尝试呈现的视图不是您从中调用它的操作的名称,并且您似乎想要返回 @987654324 @

public ActionResult DisplayFunctionsList()
    {
       var myList = F_UOF.GetAllFunctions();
        return PartialView("_DisplayFunctionList_Partial", myList);
    }

如果您在视图中(不是母版页),那么您需要传递模型,假设模型的类型正确。如果局部视图的模型是整个视图模型的属性,则只需发送模型属性而不是整个模型。

*Send Entire Model*
@Html.Partial("_DisplayFunctionList_Partial", Model)

*Send Model Property*
@{Html.Partial("_DisplayFunctionList_Partial", Model.MyList)}

【讨论】:

  • 我已经使用了@Html.RenderAction("DisplayFunctionsList", "DashboardController") 正如你所提到的,但我收到错误无法将 void 转换为对象
  • @toxic Err,这可能需要被 {}, @{Html.RenderAction("DisplayFunctionsList", "DashboardController");} 包围 - 让我验证一下
【解决方案2】:

@Html.Partial 的调用采用第二个参数,即传递给局部视图的模型。您需要做的就是将列表包含在您的视图模型中,然后适当地传递它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 2010-10-29
    • 1970-01-01
    • 2011-03-21
    • 2017-01-28
    • 1970-01-01
    相关资源
    最近更新 更多