Part 9 - Generating a radiobuttonlist control in mvc using HTML helpers

Right click on the "Models" folder and add a class file with "name=Company.cs". Copy and paste the following code.
public class Company
{
    public string SelectedDepartment { get; set; }
    public List<Department> Departments
    {
        get
        {
            SampleDBContext db = new SampleDBContext();
            return db.Departments.ToList();
        }
    }

} 


Copy and paste the following 2 "Index" action methods in HomeController class.
[HttpGet]
public ActionResult Index()
{
    Company company = new Company();
    return View(company);
}

[HttpPost]
public string Index(Company company)
{
    if (string.IsNullOrEmpty(company.SelectedDepartment))
    {
        return "You did not select any department";
    }
    else
    {
        return "You selected department with ID = " + company.SelectedDepartment;
    }
}

Right click on the "Index" action method in "HomeController" and add a view with"name=Index". Copy and paste the following code. 
@model MVCDemo.Models.Company
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm())
{
    foreach (var department in Model.Departments)
    {
        @Html.RadioButtonFor(m => m.SelectedDepartment, department.Id)@department.Name
    }
    <br />
    <br />
    <input type="submit" value="Submit" />
}

Run the application and click on "Submit" without selecting any department. Notice that, you get a message stating you have not selected any department. On the other hand, select a department and click "Submit". The selected department ID must be displayed. 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值