How to add validation errors in the validation collection asp.net mvc?

Posted by johndoe on Stack Overflow See other posts from Stack Overflow or by johndoe
Published on 2011-01-13T14:47:39Z Indexed on 2011/01/13 15:54 UTC
Read the original article Hit count: 325

Filed under:
|

Inside my controller's action I have the following code:

  public ActionResult GridAction(string id)
        {
            if (String.IsNullOrEmpty(id)) {

              // add errors to the errors collection and then return the view saying that you cannot select the dropdownlist value with the "Please Select" option

                }

            return View(); 

UPDATE:

 if (String.IsNullOrEmpty(id))
            {
                // add error 
                ModelState.AddModelError("GridActionDropDownList", "Please select an option");
                return RedirectToAction("Orders"); 
            }


        }

UPDATE 2:

Here is my updated code:

 @Html.DropDownListFor(x => x.SelectedGridAction, Model.GridActions,"Please Select") 
  @Html.ValidationMessageFor(x => x.SelectedGridAction)         

The Model looks like the following:

public class MyInvoicesViewModel
    {

        private List<SelectListItem> _gridActions; 



        public int CurrentGridAction { get; set; }

        [Required(ErrorMessage = "Please select an option")] 
        public string SelectedGridAction { get; set; } 


        public List<SelectListItem> GridActions 
        {
            get {

                _gridActions = new List<SelectListItem>(); 
                _gridActions.Add(new SelectListItem() { Text = "Export to Excel", Value = "1"}); 

                return _gridActions; 

            }
        }



    }

And here is my controller action:

 public ActionResult GridAction(string id)
        {           

            if (String.IsNullOrEmpty(id))
            {


                // add error 
                ModelState.AddModelError("SelectedGridAction", "Please select an option");
                return RedirectToAction("Orders"); 
            }

          return View(); 
        }

Nothing happens! I am totally lost on this one!

UPDATE 3:

I am now using the following code but still the validation is not firing:

  public ActionResult GridAction(string id)
        {
            var myViewModel= new MyViewModel();
            myViewModel.SelectedGridAction = id; // id is passed as null           

            if (!ModelState.IsValid)
            {
                return View("Orders");
            }

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-mvc-3