Uses Of Dropdown List And Radio Button In ASP.NET MVC Application With Entity Framework

6 minute read

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
  • 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

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=UniversityDB;User ID=sa; [email protected]" providerName="System.Data.SqlClient" />
</connectionStrings>

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

Country.cs

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

Category.cs


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

University.cs

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<University> Universities { get; set; }
    public DbSet<Category> Categories { get; set; }
    public DbSet<Country> 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

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 views given below

Create.cshtml – Modified view

@model UniversityRating.Models.University
 
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>University</h4>
 
<hr />
 
@Html.ValidationSummary(true)
<div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)</div>
</div>
<div class="form-group">
            @Html.LabelFor(model => model.CountryId, "Country", new { @class = "control-label col-md-2" })
<div class="col-md-10">
                @*@Html.DropDownList("PossibleCountries", String.Empty)*@
                @Html.DropDownList("CountryId", "Select Country")
                @Html.ValidationMessageFor(model => model.CountryId)</div>
</div>
<div class="form-group">
            <label class="control-label col-md-2">Unviersity category</label>
<div class="col-md-10">
                @foreach (var item in (IEnumerable<UniversityRating.Models.Category>)ViewBag.Categories)
                {
                    @Html.RadioButtonFor(rbtn => rbtn.CategoryId, item.Id.ToString())
                    @item.Name
}
                @Html.ValidationMessageFor(model => model.CategoryId)</div>
</div>
@*
<div class="form-group">
                @Html.LabelFor(model => model.CategoryId, "CategoryId", new { @class = "control-label col-md-2" })
<div class="col-md-10">
                    @Html.DropDownList("CategoryId", String.Empty)
                    @Html.ValidationMessageFor(model => model.CategoryId)</div>
</div>
*@
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" /></div>
</div>
</div>
}
<div>
    @Html.ActionLink("Back to List", "Index")</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Delete.cshtml

@model UniversityRating.Models.University
 
@{
    ViewBag.Title = "Delete";
}
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>University</h4>
 
<hr />
 
<dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Category.Name)
        </dt>
 
        <dd>
            @Html.DisplayFor(model => model.Category.Name)
        </dd>
 
        <dt>
            @Html.DisplayNameFor(model => model.Country.Name)
        </dt>
 
        <dd>
            @Html.DisplayFor(model => model.Country.Name)
        </dd>
 
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>
 
        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>
 
    </dl>
 
    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
<div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")</div>
}</div>

Details.cshtml


@model UniversityRating.Models.University
 
@{
    ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>University</h4>
 
<hr />
 
<dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Category.Name)
        </dt>
 
        <dd>
            @Html.DisplayFor(model => model.Category.Name)
        </dd>
 
        <dt>
            @Html.DisplayNameFor(model => model.Country.Name)
        </dt>
 
        <dd>
            @Html.DisplayFor(model => model.Country.Name)
        </dd>
 
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>
 
        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>
 
    </dl></div>
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
    @Html.ActionLink("Back to List", "Index")

Edit.cshtml : Modified

@model UniversityRating.Models.University
 
@{
    ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>University</h4>
 
<hr />
 
@Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Id)
<div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)</div>
</div>
<div class="form-group">
            @Html.LabelFor(model => model.CountryId, "Country", new { @class = "control-label col-md-2" })
<div class="col-md-10">
                @Html.DropDownList("CountryId", String.Empty)
                @Html.ValidationMessageFor(model => model.CountryId)</div>
</div>
@*
<div class="form-group">
            @Html.LabelFor(model => model.CategoryId, "CategoryId", new { @class = "control-label col-md-2" })
<div class="col-md-10">
                @Html.DropDownList("CategoryId", String.Empty)
                @Html.ValidationMessageFor(model => model.CategoryId)</div>
</div>
*@
<div class="form-group">
            <label class="control-label col-md-2">Unviersity category</label>
<div class="col-md-10">
                @foreach (var item in (IEnumerable<UniversityRating.Models.Category>)ViewBag.Categories)
                {
                    @Html.RadioButtonFor(rbtn => rbtn.CategoryId, item.Id.ToString(), Model.CategoryId == item.Id ? new { Checked = "checked" } : null)
                    @item.Name
}</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" /></div>
</div>
</div>
}
<div>
    @Html.ActionLink("Back to List", "Index")</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

__Index.cshtml__  

```csharp
@model IEnumerable<UniversityRating.Models.University>
 
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.ActionLink("Create New", "Create")
<table class="table">
<tr>
<th>
    @Html.DisplayNameFor(model => model.Name)</th>
<th>
    Country</th>
<th>
    University Category</th>
<th></th>
</tr>
@foreach (var item in Model)
    {
<tr>
<td>
    @Html.DisplayFor(modelItem => item.Name)</td>
<td>
    @Html.DisplayFor(modelItem => item.Country.Name)</td>
<td>
    @Html.DisplayFor(modelItem => item.Category.Name)</td>
<td>
    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
    @Html.ActionLink("Delete", "Delete", new { id = item.Id })</td>
</tr>
}</table>

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

<ul class="nav navbar-nav">
    <li>@Html.ActionLink("Home", "Index", "Home")</li>
    <li>@Html.ActionLink("About", "About", "Home")</li>
    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    <li>@Html.ActionLink("University", "Index", "University")</li>
</ul>

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.

Source code

Comments