在webgrid中调用javascript
本文关键字:javascript 调用 webgrid | 更新日期: 2023-09-27 18:19:22
在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
中有空格(对于前'Carrier A'),则呈现的html为:
<a id="test" onclick="alert('Carrier" src="#" A?);="">
如何格式化行以给出正确的输出?
您可以尝试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)
)
)