Thursday, 17 January 2013

Dropdownlist Validation in ASP.Net MVC 3 in Razor View

Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace DropdownListValidation.Models
{
    public class DropdownListModel
    {

        [Required( ErrorMessage = "Selection is a MUST" )]
        public string SelectedItem { get; set; }

        private List<string> _items;
        public List<string> Items
        {
            get
            {
                _items = new List<string>();
                _items.Add("One");
                _items.Add("Two");
                _items.Add("Three");
                return _items;
            }
        }
    }
}

Our Controller Class –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DropdownListValidation.Models;

namespace DropdownListValidation.Controllers
{
    public class HomeController : Controller
    {
        //Render Action
        [HttpGet]
        public ViewResult Index()
        {
            DropdownListModel model = new DropdownListModel();
            return View(model);
        }

        //Process Action
        [HttpPost]
        public ViewResult Index(DropdownListModel model)
        {
            //TODO: Validate using if(ModelState.IsValid) and process information
            return View(model);
        }
    }
}
Our View –
@model DropdownListValidation.Models.DropdownListModel

@{
    Layout = null;
}

<!DOCTYPE html>
<link rel="stylesheet" href="@Href("~/Content/Site.css")" type="text/css" />

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        <!--Render the DropDownListmodel -->
        @using (Html.BeginForm())
        {
            <p>@Html.ValidationSummary()</p>
            <p>Select an Item : @Html.DropDownListFor(x => x.SelectedItem, new SelectList(Model.Items), "--Choose any Item--" )</p>
            <input type="submit" value="Submit" />
        }

        <!-- Display Selected Item -->
         @if (!String.IsNullOrWhiteSpace(Model.SelectedItem))
         {
              <span>Selected Item : @Model.SelectedItem</span>
         }

    </div>
</body>
</html>
When you click on submit button, without selecting any value from Dropdownlist –
MVC3-RAZOR-DDL-Validation1
When we select an item and click on submit button –
MVC3-RAZOR-DDL-Validation2

No comments:

Post a Comment