DropDownList in ASP.Net MVC 4
In this
blog, I am going to explain how to create dropdownlist in the asp.net mvc 4.
Step 1
First
create an empty asp.net mvc 4 web
application and add a model class “Game” like this:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace DropDownListMvcApp.Models
{
public class Game
{
private List<SelectListItem> _game = new List<SelectListItem>();
[Required(ErrorMessage="Please select you favorite
game")]
public string SelectedGame { get; set; }
public List<SelectListItem> GameList
{
get
{
_game.Add(new SelectListItem() { Text = "Cricket", Value="Cricket"});
_game.Add(new SelectListItem() { Text = "Hockey", Value = "Hockey" });
_game.Add(new SelectListItem() { Text = "Football", Value = "Football" });
return _game;
}
}
}
}
Step 2
Now add a
controller to the project named “HomeController” to the project and write below
code to it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DropDownListMvcApp.Models;
namespace DropDownListMvcApp.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View(new Game());
}
[HttpPost]
public ActionResult Index(Game game)
{
if (ModelState.IsValid)
{
return View("Result", game);
}
else
{
return View(game);
}
}
}
}
Step 3
Now add the
view to the project named “Index” and write the below code in it:
@model DropDownListMvcApp.Models.Game
@{
ViewBag.Title =
"Index";
}
<h2>Index</h2>
<script type="text/javascript">
function selectedIndexChanged() {
}
</script>
<div>
<div>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<label>Favourite Game : </label>
@Html.DropDownListFor(m => m.SelectedGame, new SelectList(Model.GameList, "Value", "Text"), "Select
Game", new { id = "gameDropDownList", onchange = "selectedIndexChanged()" })
@Html.ValidationMessageFor(m => m.SelectedGame)
<br />
<input type="submit" value="Submit" />
}
</div>
</div>
Now add
another view to the project named “Result” to show the selected value of the
dropdownlist and write the below code in it:
@{
ViewBag.Title =
"Result";
}
<h2>Result</h2>
<div>
@ViewData.Model.SelectedGame
</div>
Your solution explorer
must look like this:
Output
Now run the application:
Click on submit will show
you error like this:
Select your favourite game
and click on submit:
Thank you for reading this article, please
put your valuable comment or any suggestion/question in the comment box.
No comments:
Post a Comment