Monday, April 19, 2021

MVC - HTML helper with RadioButtonFor method

Create ASP.NET MVC Framework 4.7 based application.

Step1. Models/Subject class

namespace Mvc_Radio_Buttons_Ex.Models
{
    public class Subject
    {
        public int subjectId { get; set; }
        public string subject { get; set; }
    }
}
Step2. Models/Student class

using System.Collections.Generic;

namespace Mvc_Radio_Buttons_Ex.Models
{
    public class Student
    {
        public string SelectedSubject { get; set; }
        public List subjects
        {
            get
            {
                List ListSubjects = new List()
                {
                new Subject(){subjectId=1, subject="Java"},
                new Subject() { subjectId = 2, subject = "PHP" },
                new Subject() { subjectId = 3, subject = "Python" },
                };
                return ListSubjects;
            }
        }
    }
}
Step3. Controllers/HomeController

using Mvc_Radio_Buttons_Ex.Models;
using System.Web.Mvc;

namespace Mvc_Radio_Buttons_Ex.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            Student s = new Student();
            return View(s);
        }

        [HttpPost]
        public string Index(Student objStudent)
        {
            if (string.IsNullOrEmpty(objStudent.SelectedSubject))
            {
                return "You did not select a subject";
            }
            else
            {
                return "You selected a subject " + objStudent.SelectedSubject ;
            }
            
        }
    }
}
Step4. Views/Index

@model Mvc_Radio_Buttons_Ex.Models.Student

@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm("index", "Home", FormMethod.Post))
{

    foreach (var subj in Model.subjects)
    {
@Html.RadioButtonFor(m => m.SelectedSubject, subj.subject) @subj.subject
}
}
OUTPUT:










No comments:

Post a Comment

Hot Topics