【问题标题】:RenderPartial Problem (While sending data to master page)RenderPartial 问题(向母版页发送数据时)
【发布时间】:2011-03-17 19:44:12
【问题描述】:

我正在尝试向母版页发送一些数据。我使用 Razor 作为我的视图引擎,并使用 AutoMapper 在域和视图模型之间进行映射。以下是我的代码:

//the partial view action method:
public ActionResult RenderCategories()
{
    IEnumerable<TopLevelCategory> categories = _categoryService.GetTopLevelCategories();
    var viewModel = new MasterPageViewModel
                    {
                        Categories =
                            Mapper.Map
                            <IEnumerable<TopLevelCategory>, IEnumerable<ParentCategory>>(categories)
                    };

    return View(viewModel);
}

//the partial view file: (this is just a test for now)
@model Sharwe.MVC.ViewModels.MasterPageViewModel

@foreach (var item in Model.Categories) {
      @item.Name
}

public class MasterPageViewModel
{
    public IEnumerable<ParentCategory> Categories { get; set; }
}

我在 _Layout.cshtml 文件中使用 @Html.RenderPartial("RenderCategories") 调用局部视图。但我不断收到以下错误:

编译器错误消息:CS1502: 最佳重载方法匹配 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' 有一些无效的参数

发生了什么事?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 razor automapper


    【解决方案1】:

    RenderPartial 扩展方法直接写入输出流并且没有返回类型 (void)。所以这里是调用它的正确语法:

    @{Html.RenderPartial("RenderCategories");}
    

    或者,如果您愿意,可以使用 Partial 扩展方法:

    @Html.Partial("RenderCategories")
    

    将它们与 WebForms 视图引擎中的等效项进行对比:

    <% Html.RenderPartial("RenderCategories"); %>
    <%= Html.Partial("RenderCategories") %>
    

    【讨论】:

    • 啊,我明白了。这确实有效,但现在局部视图的模型类型与@RenderBody 区域的模型类型冲突。有没有办法解决这个问题?
    • 您可以将正确的模型作为第二个参数传递给RenderPartial 方法。
    • 我试图这样做,但我做错了。我仍然得到同样的错误。介意给我举个例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多