Get Selected Row from ASP.NET MVC 3 WebGrid

Posted by: Malcolm Sheridan , on 2/17/2011, in Category ASP.NET MVC
Views: 127745
Abstract: The following article demonstrates how to get the selected row from the ASP.NET MVC 3 WebGrid and what to do to display data.

Every website has to display data and every website has a Grid control. In ASP.NET MVC 3 there’s the WebGrid, which is part of the Microsoft Web Helpers library. This can be downloaded through NuGet (formerly NuPack). NuGet is a free open source package manager that makes it easy for you to find, install, and use .NET libraries in your projects. One piece of functionality that is critical is reacting when the user selects an item in the WebGrid. This article will focus on finding out which row was selected, but also how to find out more about the data that is selected.

Before moving on, you need to download ASP.NET MVC 3. Click here to download and install them using the Microsoft Web Platform Installer.

Open studio 2010 and create a new ASP.NET MVC 3 Web Application (Razor) project. To focus on the answer, I’ve got a simple model as seen below.

MVC People Model Sample

Using the WebGrid, it’s easy to display this data to the user.

MVC Web Grid

The first column is the key to making this work. @item.GetSelectLink outputs a HTML anchor tag with the row selected. This is passed as a QueryString, and the name of the QueryString is set by the selectionFieldName property set on the grid.

WebGrid Query String

To find out what row is selected is just as easy. The WebGrid has a property called SelectedRow. This sets a reference to a GridViewRow object that represents the selected row in the control. When you combine this with the HasSelection property, you can get the selected row like this.

MVC GridView Row

I’ve created a partial view called _Person.cshtml. The file begins with an underscore (_) because I don’t want this file called directly from the web. The second parameter is the data being passed into the partial view. The data in this instance is the selected row.

MVC Partial View

The partial view has then got access to all the data in the selected row. Nice and easy. Thanks Microsoft!!

The entire source code of this article can be downloaded over here

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @malcolmsheridan


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Nicholas on Thursday, February 17, 2011 9:54 AM
Good one Malcolm!
Comment posted by Sumit on Thursday, February 17, 2011 9:59 AM
Thanks Malcom.

For Nuget Newbies (like me), the command exact command to download the package thru NuGet is

Install-Package microsoft-web-helpers

Cheers,
Sumit.
Comment posted by Malcolm Sheridan on Thursday, February 17, 2011 6:35 PM
@Sumit

Thanks for that.  I probably should have added that to the article.
Comment posted by Martin on Tuesday, February 22, 2011 1:25 AM
I was facing this problem at work and your webgrid article helped me out. Thank you
Comment posted by Ruslan on Tuesday, March 15, 2011 2:21 PM
hey guys how to make selectionField event, without using the Razor, i cant find anywhere similar example of using webGrid without using Razor, sounds ridicules if all people right now using Razor... :(
Comment posted by Ajit Kumar Subudhi on Tuesday, March 29, 2011 4:22 AM
http://weblogs.asp.net/andrebaltieri/archive/2010/11/02/asp-net-mvc-3-working-with-webgrid-part-2.aspx
In the above link the selection is implemented in a aspx page.

My Query here is how to display the selected item in the grid on the same page using razor engine. As I don't want to use partial view as implemented above.
I want to get the selected row item from the grid and to do some operation on it. or simple i want to show a alert message.or to display on the same page.
Comment posted by Adam Tuliper on Tuesday, May 31, 2011 10:09 AM
just curious - why name your view with an underscore? You cannot call views directly via the web anyways - they must be routable.
Comment posted by Malcolm Sheridan on Monday, September 12, 2011 8:24 AM
@Adam

I've named the view with an underscore because I don't want it called directly from a user.
Comment posted by sureshdammu on Thursday, October 13, 2011 12:53 AM
how to write dependency on dropdowns
first dropdown bind from database catename
second dropdown active productname or something in MVC Razor
Comment posted by punjabi john on Friday, November 4, 2011 12:42 AM
i use grid in a partial page and getting it by html.partial() helper.
the above code is not working in my case.

@{
    var grid = new WebGrid(source: Model,selectionFieldName:"SelectedRow",
          defaultSort: "Title",
          rowsPerPage: 25
          );
    grid.Pager(WebGridPagerModes.Numeric);
    
            }
        <div id="grid">
            @grid.GetHtml(
               tableStyle: "grid",
               headerStyle: "head",
               alternatingRowStyle: "alt",
               columns: grid.Columns(
                         grid.Column("Edit", header: null, format: @<text>@item.GetSelectLink("Edit")</text>),
                         grid.Column("Videos", format: (item) => @Html.Raw("<embed width='220' height='160' type='application/x-shockwave-flash' src='" + "http://www.youtube.com/v/" + item.VideoUrls + "'>")),
                         grid.Column("Titles")
                       , grid.Column("Add", format: (item) => Html.ActionLink("Add Record", "SaveRecord", "YTCrawler", new { url = item.VideoUrls, title = item.Titles }, null))

                            )
                        )
      </div>
</span>

@if (grid.HasSelection)
{
     Session.Add("Valuetosave",grid.SelectedRow);
}

the above grid is place in partial view.
Actually the row number selected show  i put a break point on @if (grid.HasSelection) but it never come on it.
so i need little more help
regards
punjabi
Comment posted by rajvir singh on Saturday, December 10, 2011 2:59 AM
hi sir,
pls provide the solution to how to do connectivity msaccess and mvc...... fetch record,edit,insert and delete...

Thanks in advance
Rajvir Singh
Comment posted by Andy North on Wednesday, December 28, 2011 6:43 PM
I am using this to obtain a row from a webgrid but in reality what I want to pass in is the tblusers.id rather than the row id, where tblusers.id is a field that is coming into my sql code. How would I alter the below to pass in the tblusers.id rather than the row id?

@if(grid.HasSelection){
    var user = grid.SelectedRow;
    @RenderPage("ClubAdminEditMember.cshtml", new { EUser = user } )
}

Thanks in advance for your held
Comment posted by jeff00seattle on Wednesday, May 9, 2012 2:23 PM
Thanks for the posting

I find that where I position the @if(grid.HasSelection){} code block very particular.

In my code, I have the @grid.GetHtml() wrapped within <div id="grid" style="width: 100%;"></div>

As long as the @if(grid.HasSelection){} code block is immediately after the @grid.GetHtml() code block and still within the bounds of <div id="grid" style="width: 100%;"></div>, then @RenderPage() renders fine.

However, when @if(grid.HasSelection){} is moved further down the view (even if immediately outside the bounds of <div id="grid" style="width: 100%;"></div>, @RenderPage() is called with the expected values but nothing is rendered.

Ideas?
Comment posted by robp2001 on Wednesday, May 23, 2012 9:16 AM
thanks for this code but how would i get it open in a new page when i do the grid.has.Selection?   i display all the results below the grid on the same page and i would like to open a new page with the data.

ideas?
Comment posted by robp2001 on Wednesday, May 23, 2012 9:35 AM
thanks for this code but how would i get it open in a new page when i do the grid.has.Selection?   i display all the results below the grid on the same page and i would like to open a new page with the data.

ideas?
Comment posted by sossaa3 on Friday, March 29, 2013 8:11 AM
How to select the row without "get select link", idont want any link button in my web grid . simply i want to select the row of a web grid.
Comment posted by Boyd Campbell on Thursday, April 4, 2013 9:42 AM
A great solution! It works like a charm!

However, I'm having one issue: If I repopulate the grid with a brand new set of data, the WebGrid is keeping a handle on the previously selected row. IE: When I make a run to get a totally new set of data, all of the "Selected" related API's still have a row selected. This is causing an issue in my "if ( grid.HasSelection )" since it should not be hit at all after a new set of data.

How do I "reset" the state of the grid back to an unselected state?
Comment posted by siva krishna on Monday, June 17, 2013 6:18 AM
Hi,
I am new to MVC. I wanted to display data in table format (like grid view in asp.net) With out using Entity frame work. Please suggest any site or sample example. I find many examples with entity frame work. But accordingly my requirement i can use jquery+linq+model+controller  
Comment posted by josh on Thursday, July 4, 2013 12:59 PM
nice work. there is another good example here.
http://articlesforprogramming.blogspot.in/2013/07/webgrid-in-aspnet-mvc.html
Comment posted by Sindhu` on Monday, July 22, 2013 7:58 AM
i am getting these error The best overloaded method match for 'System.Web.Helpers.WebGridRow.GetSelectLink(string)' has some invalid arguments
Comment posted by PRAVEEN on Wednesday, November 20, 2013 11:33 PM
WHAT TO DO? IF I WANT  TO GET A JQUERY UI DIALOG WINDOW ON CLICK OF EDIT??
Comment posted by PRAVEEN on Wednesday, November 20, 2013 11:52 PM
WHAT TO DO? IF I WANT  TO GET A JQUERY UI DIALOG WINDOW ON CLICK OF EDIT??
Comment posted by dgfdgfdg on Tuesday, February 25, 2014 5:31 AM
fdgdgg
Comment posted by Sanjay on Monday, April 14, 2014 2:19 AM
i want to assign that selected grid row value in text box.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel