Example of RadioButtonfor helper with entity framework
- HtmlHelper class include two extension methods to generate a <input type=”radio”> element in a razor view: RadioButton() and RadioButtonFor().
RadioButton() method Signature:
MvcHtmlString RadioButton(string name, object value, bool isChecked, object htmlAttributes)
- RadioButtonFor helper method is a strongly typed extension method. It generates <input type=”radio”> element for the property specified using a lambda expression.
RadioButtonFor() method Signature:
MvcHtmlString RadioButtonFor(<Expression<Func<TModel,TValue>> expression, object value, object htmlAttributes)
CREATE TABLE [dbo].[Category5]( [CatId] [int] IDENTITY(1,1) NOT NULL, [CategoryName] [nvarchar](max) NULL, [isselected] [bit] NULL CONSTRAINT [DF_Category5_isselected] DEFAULT ((0)), CONSTRAINT [PK_dbo.Category5] PRIMARY KEY CLUSTERED ( [CatId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace RadioButtonForEx.Models
{
using System;
using System.Collections.Generic;
public partial class Category5
{
public int CatId { get; set; }
public string CategoryName { get; set; }
public bool isselected { get; set; }
}
public class RadioButtonListClass
{
public List<Category5> radionbuttonlist { get; set; }
public string selectedradio { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RadioButtonForEx.Models;
namespace RadioButtonForEx.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
ganesha2Entities db = new Models.ganesha2Entities();
var data = db.Category5.ToList();
RadioButtonListClass obj = new RadioButtonListClass();
obj.selectedradio = "";
obj.radionbuttonlist = data;
return View(obj);
}
[HttpPost]
public ActionResult Index(RadioButtonListClass obj)
{
if(obj.selectedradio !=null)
{
Session["item"] = obj.selectedradio;
}
return RedirectToAction("ShowData");
}
public ActionResult ShowData()
{
return View();
}
}
}
@model RadioButtonForEx.Models.RadioButtonListClass
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
for(int i=0;i<Model.radionbuttonlist.Count();i++)
{
@Html.RadioButtonFor( m=>Model.selectedradio,Model.radionbuttonlist[i].CatId)
@Html.Label(Model.radionbuttonlist[i].CategoryName)
}
<input type="submit" name="name" value="Get Value" />
}
@{
ViewBag.Title = "ShowData";
}
<h2>ShowData</h2>
<h3>@Session["item"]</h3>
