In this article I will explain with an example, how to pass (send) selected WebGrid row to Controller’s Action method in ASP.Net MVC Razor.
The data from the selected WebGrid row will be fetched using jQuery and will be posted in JSON format to the Controller’s Action method using Form Submission in ASP.Net MVC Razor.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Note: For beginners in ASP.Net MVC and Entity Framework, please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example. It covers all the information needed for connecting and configuring Entity Framework.
 
Pass (Send) selected WebGrid row to Controller in ASP.Net MVC
 
 
Namespaces
You will need to import the following namespace.
using System.Web.Script.Serialization;
 
 
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 Post operation of Details View
Inside this Action method, the value of the Hidden Field is received through the customerJSON parameter.
The value of the Hidden Field contains the posted data of selected WebGrid row in serialized JSON string format.
The JSON string is de-serialized into Customer object, which is finally returned to the View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        NorthwindEntities entities = new NorthwindEntities();
        return View(entities.Customers.ToList());
    }
 
    [HttpPost]
    public ActionResult Details(string customerJSON)
    {
        Customer customer = (new JavaScriptSerializer()).Deserialize<Customer>(customerJSON);
        return View(customer);
    }
}
 
 
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.
The last column of the WebGrid consists of an ActionLink created using Html.ActionLink Helper method. The ActionLink has been specified with a CSS class which will be used as a jQuery Selector to assign a jQuery Click event handler to the ActionLink.
 
The View also consists of an HTML Form created using the Html.BeginForm helper method. The HTML Form consists of an HTML Hidden Field.
When the ActionLink is clicked, the data from the selected WebGrid row is fetched and a JSON object with property names similar to the Customer Entity class is created.
Then the JSON object is serialized into JSON string and is saved in the Hidden Field.
Finally the HTML Form is submitted to the Details Action method of the Controller.
@model IEnumerable<WebGrid_Pass_SelectedRow_Controller_MVC.Customer>
@using WebGrid_Pass_SelectedRow_Controller_MVC;
@{
    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-family: Arial;
            font-size: 10pt;
        }
        .Grid
        {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }
        .Grid th
        {
            background-color: #F7F7F7;
            font-weight: bold;
        }
        .Grid th, .Grid td
        {
            padding: 5px;
            border: 1px solid #ccc;
        }
        .Grid, .Grid table td
        {
            border: 0px solid #ccc;
        }
         .Grid a, .Grid a:visited
        {
            color:blue;
        }
    </style>
</head>
<body>
    @webGrid.GetHtml(
        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"),
                 webGrid.Column(null, null, format: @<text>@Html.ActionLink("Select", null, null, new { @class = "select" })</text>)
      ))
    @using (Html.BeginForm("Details", "Home", FormMethod.Post, new { @id = "IndexForm" }))
    {
        <input type="hidden" name="customerJSON"/>
    }
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/json2/20160511/json2.min.js"></script>
    <script type="text/javascript">
        $("body").on("click", ".select", function () {
            var row = $(this).closest("tr");
            var customer = {};
            customer.CustomerID = row.find("td").eq(0).html();
            customer.ContactName = row.find("td").eq(1).html();
            customer.City = row.find("td").eq(2).html();
            customer.Country = row.find("td").eq(3).html();
            $("[name=customerJSON]").val(JSON.stringify(customer));
            $("#IndexForm")[0].submit();
            return false;
        });
    </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_Pass_SelectedRow_Controller_MVC.Customer
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Details</title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    <table cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td valign="top" style="width:100px"><b>Selected Row: </b></td>
            <td>
                @Html.DisplayFor(model => model.CustomerID)
                <br/>
                @Html.DisplayFor(model => model.ContactName),
                @Html.DisplayFor(model => model.City)
                <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 }
        );
    }
}
 
 
Screenshot
Pass (Send) selected WebGrid row to Controller in ASP.Net MVC
 
 
Downloads