May 21, 2014

Posted in , , , ,

Free ASP.NET MVC 5.1.2 Cloud Hosting - HostForLIFE.eu - How to set an initial selected value in a RadioButtonList on ASP.NET MVC?

I have discussed about how to generate a RadioButtonList in ASP.Net MVC. If you didn’t read that, please read before proceeding this article because this is an absolute continuation of that article. Here is the link ASP.NET MVC - Generate RadioButtonList. In this article we will go over setting an initial selected value in RadioButtonList in ASP.NET MVC.
http://www.hostforlife.eu/European-ASPNET-Hosting-Free-Trial
Let’s understand this with an example. We will be using same example which we have used in the previous article. To set an initial selected value in a RadioButtonList, we can make use of IsSelected bit column in tblDepartment table. Follow below steps to get the intended output.

Step 1: Add IsSelected bit column to tblDepartment table.
ALTER TABLE tblDepartment
ADD IsSelected BIT
Step 2: Initially this column will be null for all the rows in tblDepartment table. If we want IT department to be selected by default, set IsSelected=1 for IT department row.
Update tblDepartment Set IsSelected = 1 Where Id = 1

Step 3: Refresh ADO.NET Entity Data Model.
Step 4: Finally, make the following changes to the Index View.

@model MVCDemo.Models.Company
@{
ViewBag.Title = “Index”;
}
<h2>Index</h2>
@foreach (var department in Model.Departments)
{
@Html.RadioButtonFor(m => m.SelectedDepartment, department.Id)
,(department.IsSelected.HasValue && department.IsSelected.Value)?new{@checked=”checked“}:null)@department.Name
}
Notice that @Html.RadioButtonFor helper has one more parameter to determine the initial selected value.  Run the application and we will get the output as below.
Now, if you want HR department to be selected instead of IT, set IsSelected=1 for HR department and IsSelected=0 for IT department.
Update tblDepartment Set IsSelected = 1 Where Id = 2
Update tblDepartment Set IsSelected = 0 Where Id = 1

0 comments:

Post a Comment

thanks for your comment!