MVC RadioButton
本文介绍如何创建radiobutton.
Step 1: 创建一个类用于获取所有的选项。
public class Company { public string SelectedDepartment { get; set; } public List<Department> Departments { get { SampleDataContext db = new SampleDataContext(); return db.Departments.ToList(); } } }
Step 2: 在controller文件里写入httpget and httppost方法。
[HttpGet] public ActionResult Index() { Company company = new Company(); return View(company); } [HttpPost] public string Index(Company company) { if (string.IsNullOrEmpty(company.SelectedDepartment)) { return "You didn't select any department."; } else { return "You selected department with ID = " + company.SelectedDepartment; } }
Step 3: 在view里显示radiobutton
@using (Html.BeginForm()) { foreach (var department in Model.Departments) { @Html.RadioButtonFor(m => m.SelectedDepartment, department.DepartmentID, (department.IsSelected.HasValue && department.IsSelected.Value) ? new {@checked = "checked"} : null) @department.Name <text> </text> } <br /> <br /> <input type="submit" value="Submit" /> }