Uses of Dropdown list and Radio Button in ASP.NET MVC Application with Entity Framework

Introduction
Dropdown list and Radio button are two very important controls for web. We frequently use it. In this article I will show you how to use dynamic dropdown list and radio button in CRUD operation.

Implementation Repository Pattern with ASP.NET MVC and Entity Framework
Let’s create a University Ranking application and implement Dropdown list and Radio button dynamically. Here I only show you CRUD operation on University Information page.
Tools and Technology used
I used following tools and technology to develop the project – Implementation of generic repository

  • Visual Studio 2013
  • Visual C#
  • ASP.NET MVC 5
  • Entity Framework 6
  • Razor view engine

Step 1: Create an ASP.NET MVC 5 application using Visual Studio 2013. I kept the application name “UniversityRanking”. Help: How to create first application using asp.net MVC
Step 2: Configure connection string in web.config

  
    
  

Step 3: Create three models – “Country, Category and University”

Country

    public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }

    }

Category

    public class Category
    { 
        public int Id { get; set; }
        public string Name { get; set; }
    }
[csharp]

University

[csharp]
    public class University
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [Required]
        public int CountryId { get; set; }

        [ForeignKey("CountryId")]
        public virtual Country Country { get; set; }
         [Required]
        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public virtual Category Category { get; set; }
    }

Step 4: Create a DbContext name UniversityContext in Repository folder.

    public class UniversityContext : DbContext
    {
        public UniversityContext()
            : base("DefaultConnection")
        {

        }

        public DbSet Universities { get; set; }
        public DbSet Categories { get; set; }
        public DbSet Countries { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

        }
    }

Step 5: Create a controller name – EmployeeController. Select template “MVC5 Controller with views, using entity framework”. EmployeeController will create in Controller folder and related views will be created in Views/Employee folder

01
1

Step 6: Now modify some of the action of UniversityController mentioned bellow (using comments).

    public class UniversityController : Controller
    {
        private UniversityContext db = new UniversityContext();

        // GET: /University/
        public ActionResult Index()
        {
            var universities = db.Universities.Include(u => u.Category).Include(u => u.Country);
            return View(universities.ToList());
        }

        // GET: /University/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            University university = db.Universities.Find(id);
            if (university == null)
            {
                return HttpNotFound();
            }
            return View(university);
        }

        // Modify Create Action. 
        //GET: /University/Create
        public ActionResult Create()
        {
            //ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name");
            ViewBag.Categories = db.Categories.ToList();
            ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name");
            return View();
        }

        // Modifed following action
        // POST: /University/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="Id,Name,CountryId,CategoryId")] University university)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Universities.Add(university);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch(Exception exp)
            {
                return RedirectToAction("Create");
            }

            //ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", university.CategoryId);
            //ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name", university.CountryId);
            ViewBag.Categories = db.Categories.ToList();
            ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name");
            return View(university);
        }

        // Modifed following action
        // GET: /University/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            University university = db.Universities.Find(id);
            if (university == null)
            {
                return HttpNotFound();
            }
            //ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", university.CategoryId);
            ViewBag.Categories = db.Categories.ToList();
            ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name", university.CountryId);
            return View(university);
        }

        // POST: /University/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="Id,Name,CountryId,CategoryId")] University university)
        {
            if (ModelState.IsValid)
            {
                db.Entry(university).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", university.CategoryId);
            ViewBag.CountryId = new SelectList(db.Countries, "Id", "Name", university.CountryId);
            return View(university);
        }

        // GET: /University/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            University university = db.Universities.Find(id);
            if (university == null)
            {
                return HttpNotFound();
            }
            return View(university);
        }

        // POST: /University/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            University university = db.Universities.Find(id);
            db.Universities.Remove(university);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }

Step 7: Modified some of the view given below

Create.cshtml – Modified view

@model UniversityRating.Models.University

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

University


@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.CountryId, "Country", new { @class = "control-label col-md-2" })
@*@Html.DropDownList("PossibleCountries", String.Empty)*@ @Html.DropDownList("CountryId", "Select Country") @Html.ValidationMessageFor(model => model.CountryId)
@foreach (var item in (IEnumerable)ViewBag.Categories) { @Html.RadioButtonFor(rbtn => rbtn.CategoryId, item.Id.ToString()) @item.Name } @Html.ValidationMessageFor(model => model.CategoryId)
@*
@Html.LabelFor(model => model.CategoryId, "CategoryId", new { @class = "control-label col-md-2" })
@Html.DropDownList("CategoryId", String.Empty) @Html.ValidationMessageFor(model => model.CategoryId)
*@
}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Delete.cshtml

@model UniversityRating.Models.University

@{
    ViewBag.Title = "Delete";
}

Delete

Are you sure you want to delete this?

University


@Html.DisplayNameFor(model => model.Category.Name)
@Html.DisplayFor(model => model.Category.Name)
@Html.DisplayNameFor(model => model.Country.Name)
@Html.DisplayFor(model => model.Country.Name)
@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@using (Html.BeginForm()) { @Html.AntiForgeryToken()
| @Html.ActionLink("Back to List", "Index")
}

Details.cshtml

@model UniversityRating.Models.University

@{
    ViewBag.Title = "Details";
}

Details

University


@Html.DisplayNameFor(model => model.Category.Name)
@Html.DisplayFor(model => model.Category.Name)
@Html.DisplayNameFor(model => model.Country.Name)
@Html.DisplayFor(model => model.Country.Name)
@Html.DisplayNameFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Back to List", "Index")

Edit.cshtml : Modified

@model UniversityRating.Models.University

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

University


@Html.ValidationSummary(true) @Html.HiddenFor(model => model.Id)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.CountryId, "Country", new { @class = "control-label col-md-2" })
@Html.DropDownList("CountryId", String.Empty) @Html.ValidationMessageFor(model => model.CountryId)
@*
@Html.LabelFor(model => model.CategoryId, "CategoryId", new { @class = "control-label col-md-2" })
@Html.DropDownList("CategoryId", String.Empty) @Html.ValidationMessageFor(model => model.CategoryId)
*@
@foreach (var item in (IEnumerable)ViewBag.Categories) { @Html.RadioButtonFor(rbtn => rbtn.CategoryId, item.Id.ToString(), Model.CategoryId == item.Id ? new { Checked = "checked" } : null) @item.Name }
}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Index.cshtml

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create") @foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Name) Country University Category
@Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.Country.Name) @Html.DisplayFor(modelItem => item.Category.Name) @Html.ActionLink("Edit", "Edit", new { id = item.Id }) | @Html.ActionLink("Details", "Details", new { id = item.Id }) | @Html.ActionLink("Delete", "Delete", new { id = item.Id })

Step 8: Add a link to _Layout page to access university information in Views/Shared


Step 9: Run the following command in package manager console one after another

PM> Enable-Migrations -ContextTypeName UniversityContext
PM> Add-Migration created
PM> Update-Database –Verbose

Now run application and apply CRUD operation on it using dropdownlist and radio button.

Output:
3

Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

One thought on “Uses of Dropdown list and Radio Button in ASP.NET MVC Application with Entity Framework

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>