Friday, November 26, 2010

Create a dropdownlist in asp.net MVC with Validation

In Database Section:
CREATE TABLE [dbo].[Department](
[ID] [varchar](50) NOT NULL primary key,
[Name] [varchar](50) NULL
)
CREATE TABLE [dbo].[EmployeeInformation](
[EmployeeId] [varchar](50) NOT NULL primary key,
[EmployeeName] [varchar](50) NULL,
[Salary] [decimal](18, 0) NULL,
[JoiningDate] [datetime] NULL,
[Department] [varchar](50) NULL references Department(ID),
)
In c#.net Section:
For View page createthe following metadata class......................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations.Resources;
using System.ComponentModel.Design.Serialization;


namespace ValidationCotrolTest.Models
{
[MetadataType (typeof (EmployeeInfo))]
public class EmployeeInfo
{
private String empID;
[DisplayName("Employee ID")]
[StringLength(20,ErrorMessage="Can't be longer than 20")]
[Required (ErrorMessage="Must enter ID")]

public string EmpID
{
get { return empID; }
set { empID = value; }
}
private string empName;
[StringLength (50,ErrorMessage="Can't Be Longer than 50 char")]
[DisplayName("Employee Name")]
[Required (ErrorMessage="Must Enter Name")]

public string EmpName
{
get { return empName; }
set { empName = value; }
}
private DateTime date;
[DisplayName("Joing Date")]

public DateTime Date
{
get { return date; }
set { date = value; }
}
private decimal salary;
[DisplayName ("Salary")]
[Range (1000.00,10000.00,ErrorMessage="Number Must Entered Between 1000.00 To 10000.00")]
public decimal Salary
{
get { return salary; }
set { salary = value; }
}
private List department;
[DisplayName("Select Department")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Please Select An Item")]
[Range(1, long.MaxValue, ErrorMessage = "Please Select An Item")]
public List Department
{
get { return department; }
set { department = value; }
}
}
}
In Controller Class Write the Following......................
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ValidationCotrolTest.Models;
using System.Web.UI.WebControls;
namespace ValidationCotrolTest.Controllers
{
public class EmployeeInfoController : Controller
{
// GET: /EmployeeInfo/Create

public ActionResult Create()
{
EmployeeInfo employee = new EmployeeInfo();
List departmentList = new List();
departmentList = entity.Departments.ToList();
SelectList aa = new SelectList(departmentList, "ID", "Name");

List items = new List();

items = NewMethod(aa).ToList();
items.Add(new SelectListItem { Text = "....Select...", Value = "-99", Selected = false });

employee.Department = items.OrderBy(S=>S.Value.ToString()).ToList();

return View(employee);
}

private static IEnumerable NewMethod(SelectList Departments)
{
return from department in Departments select new SelectListItem { Selected = (department.Value == "2"), Text = department.Text, Value = department.Value };
}
HRMEntities entity = new HRMEntities();
//
// POST: /EmployeeInfo/Create

[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
EmployeeInformation employee = new EmployeeInformation();
employee.EmployeeId = collection[0].ToString();
employee.EmployeeName = collection[1].ToString();
employee.Salary = Convert.ToDecimal(collection[3].ToString());
employee.JoiningDate = Convert.ToDateTime(collection[2].ToString());
employee.Department = Convert.ToString(collection[4]);
entity.AddToEmployeeInformations(employee);
entity.SaveChanges();
return RedirectToAction("Create");
}
catch
{
return View();
}
}
}
In aspx page write the following.................
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ValidationCotrolTest.Models.EmployeeInfo>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(
function () {
if (!window.mvcClientValidationMetadata) {
$('#btn').click(function () { alert("Hi"); });
}

});
</script>
<h2>
Create</h2>
<% Html.EnableClientValidation(); %>
<%: Html.ValidationSummary(true) %>
<% using (Html.BeginForm())
{%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.EmpID) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.EmpID) %>
<%: Html.ValidationMessageFor(model => model.EmpID) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.EmpName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.EmpName) %>
<%: Html.ValidationMessageFor(model => model.EmpName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Date) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Date) %>
<%: Html.ValidationMessageFor(model => model.Date) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Salary) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Salary) %>
<%: Html.ValidationMessageFor(model => model.Salary) %>
</div>
<div class="editor-label">
<%:Html.LabelFor(model => model.Department) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("Department")%>
<%: Html.ValidationMessageFor(model => model.Department)%>
</div>
<p>
<input id="btn" type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</head>
</div>
</asp:Content>


Client Side Section: Without modification  when you click will see the following message