0

I have the below action method in my controller. But seems like Model.IsValid() is always returning false even the validation conditions are ok and not showing the success message. Any help would be appreciated.

    [ActionName("CreateNewEmployeeForm")]
    [HttpPost]
    public ActionResult SaveEmployee(EmployeeViewModel employee, string btnSubmit)
    {
        switch (btnSubmit)
        {
            case "Save Employee":
                if (ModelState.IsValid)
                {
                    ViewBag.Message = "Thanks! We got your information.";
                    return View();
                }
                else
                {
                    return View();
                }
                break;
            case "Cancel":
                return RedirectToAction("EmployeeForm");
        }
        return new EmptyResult();
    }

Following are the validations I have used on entity:

    [Required(ErrorMessage ="Please Enter Your Name!")]
    [MaxLength(24)]
    [MinLength(8)]
    [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Kindly use letters only for name")]
    public string EmployeeName { get; set; }

    public string Designation { get; set; }

    [Required]
    [MaxLength(7)]
    [MinLength(4)]
    [RegularExpression("[^0-9]*$", ErrorMessage = "Salary must be numeric")]
    public decimal Salary { get; set; }

    [Required(ErrorMessage = "Please Enter Your Date Of Birth!")]
    [DataType(DataType.DateTime)]
    public DateTime DateOfBirth { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime DateCreated { get; set; }
8
  • Have you inspected your view model properties to confirm that they are indeed valid? Commented Nov 10, 2016 at 12:27
  • 3
    Just FYI, you don't need to post the form for case "Cancel", instead you should directly redirect the page to EmployeeForm using @Html.ActionLink (this will save server resources) Commented Nov 10, 2016 at 12:29
  • What validation error message you receiving? Commented Nov 10, 2016 at 12:30
  • @GauravSinghJantwal not error. the program counter is never going inside the if clause, Model.IsValid() is false always Commented Nov 10, 2016 at 13:03
  • If it's always false you have a validation error Commented Nov 10, 2016 at 13:17

4 Answers 4

1

You can try which validation cause the error:

foreach (ModelState state in employee.ModelState.Values.Where(x => x.Errors.Count > 0))
{

}
Sign up to request clarification or add additional context in comments.

Comments

0

Have you tried this? Since your ModelState.IsValid is only checking that they entered the right stuff, getting it out of the way, then do the switch stuff to determine what button they pushed.

[ActionName("CreateNewEmployeeForm")]
[HttpPost]
public ActionResult SaveEmployee(EmployeeViewModel employee, string btnSubmit)
{
    if (ModelState.IsValid)
    {
        switch (btnSubmit)
        {
            case "Save Employee":
                ViewBag.Message = "Thanks! We got your information.";
            ... where you want to send them after they submit their data
                break;
            case "Cancel":
            ... where you want to send them if they cancel (maybe back to the beginning)
                break;
        }
    }
    return View();
}

That way your switch logic won't get in the way. Check the employee model by putting a break on the if statement.

You can also put an if state to determine early if the btnSubmit == Cancel and redirect them away at that point without having to deal with the ModelState.IsValid or the switch.

4 Comments

yes, by putting breakpoints i found the flow is never hitting the if clause, always executing the else block and coming back to the form
Do you have a btnSubmit in your HttpGet ActionResult? How are you passing it? Usually, you httpget lets the user fill the form and submit it and the HttpPost handles the data that was submitted. If a user cancels, the form may be missing required values. Will the form process properly if you remove that btnSubmit variable?
You can always put a hidden field in your viewmodel that you can check in the httppost to route the user if you need to.
I have a html form with post method and that form contains 3 buttons named as btnSubmit. Now when u click it, the value of btnSubmit is going to hit the btnSubmit parameter of SaveEmployee method which has HttpPost atrtribute. MVC model binder does that for us.
0

Inspect you ModelState to see what are the error messages, another thing to mention, it is not a clean way to write one action method to serve two buttons doing two different thingsm you should create two actions.

Comments

0

it seems like your regex is not correct, the hat(^) should be outside of the bracket?

[RegularExpression("[^0-9]*$", ErrorMessage = "Salary must be numeric")]

Hope this help. :)

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.