Suppose a company has 4 departments.
The classes  are Department and Company. The codes are as follows:
Model Department.cs
namespace MvcRadioButton2.Models
{
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
Model Company.cs
using System.Collections.Generic;
namespace MvcRadioButton2.Models
{
    public class Company
    {
        public string SelectedDepartment { get; set; }
        public List<Department> Departments
        {
            get
            {
                List<Department> ListDepartments = new List<Department>()
                {
                    new Department() {Id = 1, Name="IT" },
                    new Department() {Id = 2, Name="HR" },
                    new Department() {Id = 3, Name="Marketing" },
                    new Department() {Id = 4, Name="Finance" },
                };
                return ListDepartments;
            }
        }
    }
}
Controller: HomeController.cs
using MvcRadioButton2.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcRadioButton2.Controllers
{
    public class HomeController : Controller
    {
        [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;
            }
        }
    }
}
View Index.cshtml
@model MvcRadioButton2.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" />
}
OUTPUT
 
 
 
No comments:
Post a Comment