简体   繁体   English

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

[英]How do you call a helper method with optional parameters from within a Razor View?

I've created a new html helper method for creating image tags within the razor view engine: 我创建了一个新的html helper方法,用于在razor视图引擎中创建图像标签:

    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);
    }

I think that the method is probably working, but I'm having problems calling it. 我认为该方法可能有效,但是我在调​​用它时遇到了问题。 From within my view, I have: 在我看来,我有:

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

When the view loads, I get this compiler error: 视图加载时,出现此编译器错误:

CS0103: The name 'style' does not exist in the current context CS0103:名称“样式”在当前上下文中不存在

What is the correct syntax for using optional parameters within a razor view? 在剃刀视图中使用可选参数的正确语法是什么?

You are not using a valid C# syntax. 您没有使用有效的C#语法。 Use : instead of = to specify the value of an optional argument: 使用:而不是=来指定可选参数的值:

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

Further reading: Named and Optional Arguments (C# Programming Guide) 进一步阅读: 命名和可选参数(C#编程指南)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM