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);
    }
Rasik
  • 1,961
  • 3
  • 35
  • 72
  • 3
    As an aside, it is highly recommended you format your code cleanly so people can quickly and accurately understand what you're doing! – Nathaniel Ford Aug 08 '15 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. – ataravati Aug 08 '15 at 16:06
  • Not It didnot work! I can Redirect to Create Action without Selecting any Value from the Drop Down. – Rasik Aug 08 '15 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. – Michael Fürstenberg Aug 08 '15 at 19:32
  • Yeah!! Exactly... Please help with this scenario – Rasik Aug 09 '15 at 01:22

3 Answers3

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--")
Community
  • 1
  • 1
  • What should be added to the Controller ? – Rasik Aug 09 '15 at 01:28
  • Do your mean to populate the `SelectList`? If so, its just what you currently using to assign `ViewData["monthType"]` –  Aug 09 '15 at 01:32
  • Your Solution Wont' Give My answer!! But Thank you – Rasik Aug 09 '15 at 01:41
  • 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. –  Aug 09 '15 at 01:49
  • @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 – Rasik Aug 09 '15 at 01:52
  • Sorry - typo in my code - it should be `m => m.month_id` –  Aug 09 '15 at 01:57
  • And is anything wrong on my code?? Usually i used to copy all the property from the model generated by the EF and called it as a view model and all the CRUD operation is done from that Classes. – Rasik Aug 09 '15 at 01:59
  • Nothing as a piece of code (although declaring `mat` as null initially is pointless, as is the extra overhead of `.ToList()` since all you want is `IEnumerable`). Its just does not belong in a view model (impossible for example to write unit tests) - it belongs in the controller. –  Aug 09 '15 at 02:05
  • In this section of Code i want to fetch the list of the month stored in databases. how could i do this ? public class Repository { public static List FetchMonths() { List months = new List() { new Month(){ ID = 1, Name = "January" }, new Month(){ ID = 2, Name = "February" }, new Month(){ ID = 3, Name = "March" }, new Month(){ ID = 4, Name = "April" } }; return months; } } – Rasik Aug 09 '15 at 04:25
  • Your Codes on fiddle works fine !! but in my code whenever i press the save button without selecting any value, it generates validation error message but also display "You hit the Controller".. Please help – Rasik Aug 09 '15 at 05:29
  • First thing to check is that you have the correct scripts, and in the correct order - `jquery{version}.js`, `jquery.validate.js` and `jquery.validate.unobtrusive.js` –  Aug 09 '15 at 05:33
  • Wow!!! Every things work fine now! Thank You Very very much...Would you help again with further Question ? – Rasik Aug 09 '15 at 05:45
  • Sure, but you will need to ask a new question (not continue this thread). Add a link to it here when your done and I'll have a look :) –  Aug 09 '15 at 05:50
  • Sorry!! one more question, Now, how do i Redirect to Create Action after Selecting the Valid Option, and make the month_id available for insertion after the create action is completed. – Rasik Aug 09 '15 at 05:54
  • I would need to see more code to be sure (which is why you should ask a new question). Your view has `@using(Html.BeginForm("Create","Talab",FormMethod.Post))` so its posting to the `Create()` method. Assuming your using the `SalaryViewModel` as per my answer, If that method is `public ActionResult Create(SalaryViewModel model)` then `model.month_id ` will contain the selected value. –  Aug 09 '15 at 06:06
  • If it would be possible i would send you a whole file? and you can answer me and i would fix it. – Rasik Aug 09 '15 at 06:16
  • http://stackoverflow.com/questions/31902230/system-collections-generic-keyvaluepairstring-system-web-mvc-modelstate-error i have added a new question.. Please have a look!! – Rasik Aug 09 '15 at 08:13
  • http://stackoverflow.com/questions/32635218/how-to-detect-the-request-body-is-either-missing-or-broken-in-web-api please help!! – Rasik Sep 17 '15 at 16:36
  • @aakash, The question you linked to cannot be answered because you have not even explained what your doing, e.g. are you sending this object as part of an ajax call. And you have not even shown the controller method. –  Sep 18 '15 at 00:49
1

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

Community
  • 1
  • 1
Stephen King
  • 816
  • 4
  • 14
  • Why are you making `id` nullable when it's required? – John H Aug 08 '15 at 16:19
  • 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"` –  Aug 08 '15 at 23:48
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?

Community
  • 1
  • 1
gvk
  • 597
  • 7
  • 27