c# - 如何使用MVC4在部分 View 中调用HtmlHelper方法

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

我是 Mvc4 的新手。基本上我想要创建具有菜单和子菜单的动态选项卡。

这是我的 Htmlhelper 类:

namespace DBMvc.Htmlhlpr
{
public static class HtmlHelperExtension
{
    public static String ParentMenus(this HtmlHelper html, IEnumerable<menu> Menu)
    {
        string htmlOutput = string.Empty;
        if (Menu.Count() > 0)
        {
            htmlOutput += "<ul class='sf-menu'>";
            var Mainmenu = from mainMenu in Menu where mainMenu.Catid == null select mainMenu;
            foreach (menu m in Mainmenu)
            {
                htmlOutput += "<li>";
                htmlOutput += LinkExtensions.ActionLink(html, m.Depname, null);
                htmlOutput += SubMenus(html, Menu, m.Depid);
                htmlOutput += "</li>";

            }
            htmlOutput += "</ul>";
        }
        return htmlOutput;
    }
    private static string SubMenus(this HtmlHelper html, IEnumerable<menu> SubMenu, int Catid)
    {
        string htmlOutput = string.Empty;
        var subMenu = from sm in SubMenu where sm.Depid ==Catid orderby sm.cats select sm;
        if (subMenu.Count() > 0)
        {
            htmlOutput += "<ul>";
            foreach (menu m in subMenu)
            {
                htmlOutput += "<li>";
                htmlOutput += LinkExtensions.ActionLink(html, m.Depname, null);
                htmlOutput += SubMenus(html, SubMenu, m.Catid);
                htmlOutput += "</li>";
            }
            htmlOutput += "</ul>";
        }
        return htmlOutput;}}}}

我的 Controller 是:

public class FrontController : Controller
{
   // MenuEntities MEnt = new MenuEntities();
    NewDatabaseEntities Db = new NewDatabaseEntities();
   // menu MEnt  = new menu();
   // [ChildActionOnly]
    public ActionResult Menu()
    {
        var mMenu = Db.Dep_Table.ToList();
        return PartialView(mMenu)
    }
}

在部分 View 中,我想使用 @Html.Raw 调用 htmlhelper 方法“ParentMenus”。我不知道该怎么做。

最佳答案

有两件事:

  1. 我建议更改您的 HTML Helper 以返回包含 HTML 的 HtmlString。然后您可以避免使用 @Html.Raw(),这几乎总是一种不好的做法(尽管它有其目的)。

  2. 在 Razor View 页面(CSHTML 文件)中,将 @using DBMvc.Htmlhlpr 放在文件顶部,以确保已导入帮助程序命名空间。然后调用助手使用@Html.ParentMenus(...)

第 1 项并不是绝对必要的,但它是所有内置 HTML 帮助程序所做的事情,并且通常是一个很好的做法。

如果不是这样,请指出您遇到的错误(如果有)。

关于c# - 如何使用MVC4在部分 View 中调用HtmlHelper方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25519186/

相关文章:

c# - 单个 WebClient 实例的证书验证逻辑

c# - 为什么 FakeItEasy 抛出这个异常,为什么使方法成为虚拟方法来修复它?

html - 如何将查询参数和类属性传递给 MVC3 中的 Html.BeginForm?

c# - 在 MVC.Net 中链接 lambda 表达式,而无需重复传递 HtmlHelper 对象

c# - Silverlight Web 应用程序未处理的异常代码 4004

c# - 如何在我的 REST WCF 服务中接受任意 JSON 对象?

c# - SSRS DataSourceCredentials 和 Windows 身份验证

c# - 从两个不同的输入上传两个不同的文件

c# - 无法访问存储在我的 App_Data 文件夹中的图像

c# - 无法将类型 'void' 隐式转换为 'object' asp.net.MVC