Radio Buttons in WebGrid MVC

In the previous article we have discussed about how to embed jQuery UI Spinner control, TextArea and TextBox control in the MVC WebGrid. And Now in the following example we’ll see that how to show the radio buttons in the WebGrid.

radio buttons in webgrid mvc

As you can see below, i am adding a new column with the format parameter which will create the radio button in the first column of the WebGrid. The code will be render as shown in the picture.

<div id="EmployeeViewGrid">
            @{  
                var grid1 = new WebGrid(source: Model, canPage: true);
        @grid1.GetHtml(mode: WebGridPagerModes.All, tableStyle: "webGrid",
            headerStyle: "header",
            alternatingRowStyle: "alt",
            selectedRowStyle: "select",
            rowStyle: "row",
            htmlAttributes: new { id = "employeeGrid" },
            fillEmptyRows: false,
 
            columns: grid1.Columns(
             grid1.Column("EmployeeId",format: (item) => Html.RadioButton("EmployeeId",
                 (int)item.Salary, new { @class = "radio" }), header: "Select"),
             grid1.Column("EmployeeId", header: "EmployeeId"),
             grid1.Column("EmpName", header: "EmpName"),
             grid1.Column("Age", header: "Age"),
             grid1.Column("Salary",header: "Salary")))
            }
</div>

In the WebGrid(i am rendering from the above code), user will be able to checked only one radio button among the rows because all radio button have the same name (you can see the rendered html of the table).
For it, we need to give the unique name to the each radio button. so i am adding the employeedId along with their names as:

grid1.Column("EmployeeId", format: (item) => Html.RadioButton("EmployeeId",
                (int)item.EmployeeId, 
                new { @class = "radio",
                      @id="emp" + item.EmployeeId,
                      @Name="emp" + item.EmployeeId }), 
                header: "Select"),

multiple selection in webgird mvc

Using the same concept you can now easily embed various controls in the WebGrid.

Try yourself the following exercise:

WebGrid with CheckBox

Do your self and send me your code. I will review your code or help you if will face any problem. Thanks