在webgrid中调用javascript

时间:2012-01-01 17:39:16

标签: c# javascript asp.net asp.net-mvc-3 webgrid

我无法在webgrid中调用javascript函数

<%= gridColumns.Add(grid.Column("CarrierName", "CarrierName",  
 format: (item) => new HtmlString("<a src='#' id='test'   
onclick=alert('"+item.CarrierName+"');>"+ (string)item.CarrierName + "</a>"))); %>

如果CarrierName中有空格(对于前'运营商A'),则呈现的html为:

<a id="test" onclick="alert('Carrier" src="#" A?);="">

如何格式化行以提供正确的输出?

1 个答案:

答案 0 :(得分:3)

您可以尝试JSON编码:

<%= gridColumns.Add(
    grid.Column(
        "CarrierName", 
        "CarrierName",  
        format: (item) => new HtmlString("<a src='#' id='test' onclick='alert(" + Json.Encode(item.CarrierName) + ");'>" + Html.Encode(item.CarrierName) + "</a>")
    )) 
%>

但是我会尝试通过编写一个生成锚点的自定义HTML帮助程序来避免这个标记:

public static class HtmlExtensions
{
    public static IHtmlString Link(this HtmlHelper htmlHelper, MyViewModel item)
    {
        var anchor = new TagBuilder("a");
        anchor.AddCssClass("test");
        anchor.Attributes["src"] = "#";
        anchor.Attributes["onclick"] = string.Format(
            "alert({0});", Json.Encode(item.CarrierName)
        );
        anchor.SetInnerText(item.CarrierName);
        return new HtmlString(anchor.ToString());
    }
}

然后:

grid.Columns(
    grid.Column(
        "CarrierName",
        "CarrierName",
        format: item => Html.Link((MyViewModel)item.Value)
    )   
)