如何在Razor视图中调用带有可选参数的辅助方法?

rec*_*ive 2 c# optional-parameters razor asp.net-mvc-3

我已经创建了一个新的html辅助方法,用于在剃刀视图引擎中创建图像标记:

    public static MvcHtmlString Image(this HtmlHelper helper, string fileName, string altText, 
        string cssClass = null, string id = null, string style = null)
    {
        var server = HttpContext.Current.Server;
        string location = server.MapPath("~/Content/Images/" + fileName);
        var builder = new TagBuilder("img");
        builder.Attributes["src"] = location;
        builder.Attributes["alt"] = altText;

        if (!string.IsNullOrEmpty(cssClass))    builder.Attributes["class"] = cssClass;
        if (!string.IsNullOrEmpty(id))          builder.Attributes["id"] = id;
        if (!string.IsNullOrEmpty(style))       builder.Attributes["style"] = style;

        string tag = builder.ToString(TagRenderMode.SelfClosing);
        return new MvcHtmlString(tag);
    }
Run Code Online (Sandbox Code Playgroud)

我认为这种方法可能有效,但我在调用它时遇到了问题.在我看来,我有:

@Html.Image("getstarted-promo.jpg", "Get Started", style = "width: 445; height: 257;")
Run Code Online (Sandbox Code Playgroud)

加载视图时,我收到此编译器错误:

CS0103:当前上下文中不存在名称"style"

在剃刀视图中使用可选参数的正确语法是什么?

Dar*_*rov 6

您没有使用有效的C#语法.使用:而不是=指定可选参数的值:

@Html.Image("getstarted-promo.jpg", "Get Started", style: "width: 445; height: 257;")
Run Code Online (Sandbox Code Playgroud)

进一步阅读:命名和可选参数(C#编程指南)