Tuesday, August 28, 2012

asp.net mvc 4 - webgrid add it as reference and use javascript in it

1. To use @Html.WebGrid in the razor view page by default it won't be loaded.
The webgrid is in System.Web.Helper, and it needs to be added in web.config like below in system.web section,

< compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>


2. By default, you can use format: (item) => item.GetSelectLink()) to add a select link for each row.

However, I want to add a javascript function to pass an itemId, then open a jquery ui dialog to load the values and save it by Json format.

You can use HtmlString to override it, format: (item) => new HtmlString("<a href=# onclick=...")

A cleaner way will be create a htmlHelperExtension to return the html string, such as,

    public static class HtmlExtension
    {
        public static IHtmlString Link(this HtmlHelper htmlHelper, Post item)
        {
            var anchor = new TagBuilder("a");
            anchor.AddCssClass("sel");
            anchor.Attributes["src"] = "#";
            anchor.Attributes["onclick"] = string.Format("select({0});", item.Id);
            anchor.SetInnerText("select");
            return new HtmlString(anchor.ToString());
        }
    }

Then in the razor view page, it will become format:(item) => Html.Link((Post)item.Value)
The namespace for the HtmlExtension should be declared, and remember to pass item.Value.

No comments: