1

I am having trouble calling javascript function in webgrid

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

Id the CarrierName has spaces (for ex 'Carrier A') in it, the rendered html is :

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

How do i format the row to give a proper output ?

1 Answer 1

3

You could try JSON encoding it:

<%= 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>")
    )) 
%>

But I would try to avoid this tag soup by writing a custom HTML helper that will generate the anchor:

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

and then:

grid.Columns(
    grid.Column(
        "CarrierName",
        "CarrierName",
        format: item => Html.Link((MyViewModel)item.Value)
    )   
)
Sign up to request clarification or add additional context in comments.

3 Comments

json rendered it as : <a id="test" onclick="alert('"Carrier" A??);="" src="#">
working with replacing the whitespace with a character. Cannot put the html helper (dont have a say in it )
this method would not be workable with grids, since the Html Extensions are not supported directly. you would need to call the method name from class refrence and not as extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.