3

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);
    }
5
  • 3
    As an aside, it is highly recommended you format your code cleanly so people can quickly and accurately understand what you're doing! Commented Aug 8, 2015 at 16:01
  • Just use the RequiredAttribute like any other input. The validation doesn't have anything to do with drop-down list or text box or whatever input you use. Commented Aug 8, 2015 at 16:06
  • Not It didnot work! I can Redirect to Create Action without Selecting any Value from the Drop Down. Commented Aug 8, 2015 at 16:19
  • If I understand you correctly, you want the Create link to be disabled if a month is not set in the drop-down list? Then you will have to validate with javascript. Commented Aug 8, 2015 at 19:32
  • Yeah!! Exactly... Please help with this scenario Commented Aug 9, 2015 at 1:22

3 Answers 3

3

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--")
Sign up to request clarification or add additional context in comments.

19 Comments

What should be added to the Controller ?
Do your mean to populate the SelectList? If so, its just what you currently using to assign ViewData["monthType"]
Your Solution Wont' Give My answer!! But Thank you
What do you mean wont give you the answer. Read the first paragraph. You binding to a property named month_id which is nullable but you don't have the required attribute so anything you select (including the "--Select a Month--" option) IS VALID. It is the CORRECT answer! The side note just points out how you should be doing it.
@Html.DropDownListFor(model => model.Month.id, Model.MonthList, "--Select a Month--") ... Where is month_id... ?? drop down has nothing to do with month_id..if the month is selected, the id of that month is copied to month_id which is the property of Salary. otherwise, the Create link should be disabled
|
2

Make sure you use required on the model.

[Required]
public int id { get; set; }

Validating required selection in DropDownList

https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.requiredattribute(v=vs.110).aspx

2 Comments

Why are you making id nullable when it's required?
If it's int then the date-val-required attribute is added by default - a property that is typeof int is always required because it cant be null. The [Required] attribute is unnecessary unless you want to override the default error message using ErrorMessage="someMessage"
1

Specify the range attribute

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

Source : MVC3 validation with data-annotation?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.