Razor 输出在 MVC 3 中不起作用,但在 MVC 2 中起作用 [英] Razor output not working in MVC 3 but working in MVC 2

查看:36
本文介绍了Razor 输出在 MVC 3 中不起作用,但在 MVC 2 中起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同样的代码在 MVC 2 中运行良好,但在 MVC 3 Razor 中不起作用.加载页面后,不会从 Razor 中调用的 HTMLHelper 加载菜单,如下所示.

This same code working fine with MVC 2 but not working in MVC 3 Razor. Once page is loaded not loading menu from HTMLHelper called within Razor like below.

用于测试的硬编码菜单未在页面上输出.

Hardcoded menu for testing which is not outputting on the page.

using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using myproject.Extensions;

public static class MenuHelper
{

    public static string TabbedMenu(this HtmlHelper helper, IEnumerable<MenuTab> tabs)
    {
       //I have hard coded menu for testing purpose.

        return "<div class='menu-image'><img src='/content/Images/common/on-left.gif' alt='' /></div><div class='on'><a class='over' href='/?Length=4'>Home</a></div><div class='menu-image'><img src='/content/Images/common/on-right.gif' alt='' /></div><a href='/Home/About'>About</a><a href='/Home/Contact'>Contact</a>";
    }

}

以下是 Razor CSHTML 代码.

Below is Razor CSHTML code.

 @{Html.TabbedMenu
                        (
                            new List<MenuTab>
                            {
                                MenuTab.Create("Home", "Index", "Home"),
                                MenuTab.Create("About", "About", "Home"),
                                MenuTab.Create("Contact", "Contact", "Home")
                            }
                        );}

推荐答案

@{ ... } 中包装代码(就像你所做的那样)是 Razor 等价于 <% ... %>(没有 =).

Wrapping code in @{ ... } (like you did) is Razor's equivalent to <% ... %> (without an =).

因此,您的代码调用了该函数,但不会对结果执行任何操作.

Therefore, your code calls the function, but doesn't do anything with the result.

您应该删除 {}; 并简单地编写 @Html.TabbedMenu(...);这相当于 <%: Html.TabbedMenu(...) %>.

You should remove the {} and the ; and simply write @Html.TabbedMenu(...); this is equivalent to <%: Html.TabbedMenu(...) %>.

您还需要更改方法以返回 HtmlString 以防止 Razor 转义 HTML.

You'll also need to change the method to return an HtmlString to prevent Razor from escaping the HTML.

这篇关于Razor 输出在 MVC 3 中不起作用,但在 MVC 2 中起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆