我在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?);="">
如何格式化该行以提供适当的输出?
最佳答案
您可以尝试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)
)
)
关于c# - 在webgrid中调用JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8694468/