Rasik
Rasik

Reputation: 2410

How To Validate DropDown List in Asp .net MVC

The List of the month are Already added In Databases. For Adding the salary (Create operation), i have to select the month type from the Drop Down List, if the month is not selected the program should not have to redirect to create action. How Can i validate the Drop Down, Before Routing to Create Action ?

@using(Html.BeginForm("Create","Talab",FormMethod.Post))
{ 
    <div class="row">
        <div class="form-group">
            <div class="col-md-2">
                <a href="@Url.Action("Create","TotalSalary")" class="btn btn-success input-sm">Add New </a>
            </div>
        </div>
        <div class="form-group">   
            <div class="col-md-2">
                @Html.DropDownListFor(model => model.Month.id,     (IEnumerable<SelectListItem>)ViewData["monthType"], "--Select a Month--")
                @Html.ValidationMessageFor(model => model.Month.id)
            </div>
        </div>
    </div>
}

My View Model has following Property

public class Salary
{
   public int id { get; set; }
   public Nullable<int> month_id { get; set; }

   [Required]
   public virtual Month Month { get; set; }

   public IEnumerable<Month> GetMonths()
   {
        IEnumerable<Month> mat = null;
        mat = this.db.Months.ToList();
        return mat;
   }

}
Public Class Month
{
    public int id { get; set; }
    public string month { get; set; }
    public virtual ICollection<Salary> Salary { get; set; }
}

My Controller Action Index

public ActionResult Index()
    {
        Salary salary = new Salary();
        ViewData["monthType"] = salary .GetMonths().ToList().Select(
                 s => new SelectListItem
                 {
                     Text = s.month,
                     Value = s.id.ToString()
                 });

        return View(salary);
    }

Upvotes: 3

Views: 12010

Answers (3)

user3559349
user3559349

Reputation:

Your dropdownlist should bind to property month_id which is Nullable<int>, but you have not decorated it with the [Required] attribute. It needs to be

[Required(ErrorMessage="Please select a month")]
public Nullable<int> month_id { get; set; } 

and in the view

@Html.DropDownListFor(m => m.month_id, ....)
@Html.ValidationMessageFor(m => m.month_id)

Side note: You claim your using a view model, but in fact your not. What you have shown is a data model. A view model contains only properties relevant to your view and should never contain method that access your database. Refer What is ViewModel in MVC?

A view model in your case would be

public class SalaryViewModel
{
  public int id { get; set; }
  [Required(ErrorMessage="Please select a month")]
  [Display(Name = "Month")] // for use in @Html.LabelFor()
  public Nullable<int> month_id { get; set; }
  public SelectList MonthList { get; set; } // or IEnumerable<SelectListItem> MonthList
}

Where you populate the MonthList property in the controller and use it in the view as

@Html.DropDownListFor(m => m.month_id, Model.MonthList, "--Select a Month--")

Upvotes: 3

gvk
gvk

Reputation: 617

Specify the range attribute

[Required]
[Range(1, 12, ErrorMessage="Please select a value")]
public int Id { get; set; }

Source : MVC3 validation with data-annotation?

Upvotes: 1

Related Questions