Make WebGrid row Clickable using jQuery in ASP.Net MVC


A Client Side click event handler will be attached to the WebGrid row using jQuery and thus when the WebGrid row is clicked, it will redirect to another View in ASP.Net MVC Razor.


A Client Side click event handler will be attached to the WebGrid row using jQuery and thus when the WebGrid row is clicked, it will redirect to another View in ASP.Net MVC Razor

Controller
The Controller consists of two Action methods.
Action method for handling GET operation of Index View
The Entity Framework is now configured and hence now we can create a Controller and write code to fetch the records from the Customers Table of the Northwind Database.
Inside the Index Action method, the Customer records are fetched using Entity Framework and returned to the View.
 
Action method for handling GET operation of Details View
Inside this Action method, the value of the CustomerId is fetched from the RouteData collection and is used to fetch the Customer’s record using Entity Framework.
Finally the Customer’s record is returned to the View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        NorthwindEntities entities = new NorthwindEntities();
        return View(entities.Customers.ToList());
    }
 
    public ActionResult Details()
    {
        string customerId = RouteData.Values["id"].ToString();
        NorthwindEntities entities = new NorthwindEntities();
        return View(entities.Customers.Find(customerId));
    }
}
 
 
Index View
Inside the Index View, in the very first line the Customer Entity is declared as IEnumerable which specifies that the Model will be available as a Collection.
The WebGrid is initialized with the Model i.e. IEnumerable collection of Customer Entity class objects as source.
The WebGrid is created using the GetHtml method with the following parameters.
HtmlAttributes – It is used to set the HTML attributes to the HTML Table generated by WebGrid such as ID, Name, Class, etc.
Columns – It is used to specify the columns to be displayed in WebGrid and also allows to set specific Header Text for the columns.
A Client Side click event handler will be attached to the WebGrid row using jQuery and thus when the WebGrid row is clicked, it will redirect to the Details View in ASP.Net MVC Razor.
Note: For information on highlighting WebGrid row on Mouseover (Mouser Hover), please refer my article Highlight row of WebGrid on Mouseover (Mouse Hover) using CSS in ASP.Net MVC.
 
@model IEnumerable<WebGrid_Row_Clickable_MVC.Customer>
 
@{
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canSort: false);
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body
        {
            font-familyArial;
            font-size10pt;
        }
        .Grid
        {
            border1px solid #ccc;
            border-collapsecollapse;
        }
        .Grid th
        {
            background-color#F7F7F7;
            font-weightbold;
        }
        .Grid th.Grid td
        {
            padding5px;
            border1px solid #ccc;
        }
        .Grid.Grid table td
        {
            border0px solid #ccc;
        }
        .Grid th a.Grid th a:visited
        {
            color#333;
        }
        .Grid .row:hover td
        {
            background-colorgold;
            cursorpointer;
        }
    </style>
</head>
<body>
    @webGrid.GetHtml(
        rowStyle: "row",
        alternatingRowStyle: "row",
        htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
        columns: webGrid.Columns(
                 webGrid.Column("CustomerID""Customer Id"),
                 webGrid.Column("ContactName""Customer Name"),
                 webGrid.Column("City""City"),
                 webGrid.Column("Country""Country")
      ))
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("body").on("click""#WebGrid td"function () {
            var customerId = $(this).closest("tr").find("td:first").html();
            window.location = "/Home/Details/" + customerId;
        });
    </script>
</body>
</html>
 
 
Details View
Inside the Details View, in the very first line the Customer Entity is declared as Model for the View. The details of the Customer is displayed using the Html.DisplayFor helper method.
@model WebGrid_Row_Clickable_MVC.Customer
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Details</title>
    <style type="text/css">
        body
        {
            font-familyArial;
            font-size10pt;
        }
    </style>
</head>
<body>
    <table cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td valign="top" style="width:65px"><b>@Html.DisplayNameFor(model => model.Address):</b></td>
            <td>
                @Html.DisplayFor(model => model.Address)
                <br/>
                @Html.DisplayFor(model => model.City),
                @Html.DisplayFor(model => model.PostalCode)
                <br/>
                @Html.DisplayFor(model => model.Country)
            </td>
        </tr>
    </table>
</body>
</html>
 
 
Mapping Routes for the Details View
You will need to map a route for the Details View by making use of the MapRoute function as shown below.
This is necessary as otherwise the Routing won’t work for the Details View when the ActionLink in WebGrid is clicked.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
 
        routes.MapRoute(
            name: "Details",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Details", id = UrlParameter.Optional }
        );
    }
}

Comments

Popular posts from this blog

Automatically send Birthday email using C#.Net

Drag and Drop multiple File upload using jQuery AJAX in ASP.Net using C# and VB.Net

Difference between each and map in jquery