【问题标题】:How to pass action name from controller to view如何将动作名称从控制器传递到视图
【发布时间】:2015-12-18 07:11:28
【问题描述】:

我是 razor 的新手,我需要帮助才能将动作名称从控制器传递到使用 ViewBag 进行查看。以下是我的代码:

    public ActionResult Index(int id = 0)
    {
        ViewBag.MasterId = id;
        ViewBag.ActionName = "ApplicationProcess";
        return View();
    }

从上面的动作方法中,我传递了在视图中使用的动作名称,该视图在此函数的结果中呈现。

<body>
    <h2>Index</h2>
    <div style="width: 1100px;">
        <div style="float: left; width: 400px;">
            @{Html.RenderAction("MasterRecordProcess", "Process");}
        </div>
        <div style="float: right">
            @{Html.RenderAction("MasterRecordBasicInfo", "Process", new { id = ViewBag.MasterId });}
        </div>
        <div style="float:right;margin-top:50px;" class="task-div">
            @{Html.RenderAction(@ViewBag.ActionName, "Process", null);}
        </div>
    </div>
</body>

现在在上面的视图中,我想使用 Html.RenderAction 中的控制器传递的 ViewBag.ActionName 但这给了我错误消息。

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper<OAC.Areas.Personal.Models.MasterModel>' has no applicable method named 'RenderAction' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

请帮助我如何在 viewBag 对象中呈现从控制器传递的动作名称。谢谢。

【问题讨论】:

  • 将其转换为字符串 - (string)ViewBag.ActionName

标签: asp.net-mvc razor


【解决方案1】:

正如@Stephen 所说,您必须首先投射视图包内容:

@{
    var actionName= (string)ViewBag.ActionName;
}

然后就可以使用了:

@{Html.RenderAction(actionName, "Process", null);}

【讨论】:

    【解决方案2】:

    错误本身表明“考虑强制转换动态参数或在没有扩展方法语法的情况下调用扩展方法。

    当任何参数是动态类型时,C# 不支持调用扩展方法 (Html.RenderAction())。您必须静态调用扩展方法或将参数转换为非动态类型。

    在这种情况下,您可以将ViewBag 转换为String 并使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多