Tuesday, July 22, 2014

Populate DropDownList with Enum in ASP.Net MVC 4

Populate DropDownList with Enum in ASP.Net MVC 4

In this blog, I am going to explain how to populate the drop down list with enum in the asp.net mvc 4.

You can also view my other blog on drop down list on below link:

Step 1

First create an empty asp.net mvc 4 web application and add a model class named ”Game” in it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DropDownListWithEnumMvcApp.Models
{
    public class Game
    {

        public IEnumerable<SelectListItem> GameList { get; set; }
    }

    public enum GameType
    {
        Cricket = 1,
        Football = 2,
        Hockey = 3
    }
}

Here you can see I have created an enum named “GameType”.

Step 2

Now add a controller to the project named “HomeController” and write the below code in it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DropDownListWithEnumMvcApp.Models;

namespace DropDownListWithEnumMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            IEnumerable<GameType> gameType = Enum.GetValues(typeof(GameType)).Cast<GameType>();

            Game _game = new Game();

            _game.GameList = from game in gameType select new SelectListItem { Text = game.ToString(), Value = game.ToString() };

            return View(_game);
        }

        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            ViewBag.Message = form["gameList"].ToString();
            return View("Result");
        }
    }
}

Step 3

Now add a view to the project named “Index” and it will be strongly typed view like this:

@model DropDownListWithEnumMvcApp.Models.Game

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div>
    <div>
        @using (Html.BeginForm("Index", "Home", FormMethod.Post))
        {
            <label>Favorite Game : </label>
            @Html.DropDownListFor(m => m.GameList, Model.GameList, new { id="gameList"})
            <br />
            <input type="submit" value="Submit"/>
        }
    </div>
</div>

Step 4

Now add another view to the project named “Result” and write below code in it:

@{
    ViewBag.Title = "Result";
}

<h2>Result</h2>

<div>
    @ViewBag.Message
</div>


Your solution explorer will look like this:



Output

Now run the application



Select your favourite game and click on submit button:




Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box. 




No comments:

Post a Comment