Lost
Lost

Reputation: 13645

Showing Validation Errors using MVC

I have been trying to display validation errors using MVC's inherent validation framework. I am using following code for my Controller:

[HttpPost]
        public ActionResult SaveApplication(ApplicationModel application)
        {
            if (!ModelState.IsValid)
            {                   
                return View("New",application);
            }

            ApplicationBLL.SaveApplication(application);
            return Content(string.Empty);
        }

While my view looks like:

<tr>
        <td>Name</td>
        @Html.ValidationSummary(true)
        <td>@Html.TextBoxFor(m => m.Name)</td>
        <td>@Html.ValidationMessageFor(m => m.Name, "Name is required")</td>
    </tr>

following is how the model class looks like:

public class  ApplicationModel
    {
        public int ApplicationId { get; set; }

        public string ApplicationNumber { get; set; }

        [Required]
        public string Name { get; set; }

        public DateTime EventDate { get; set; }

        public string EventAddress { get; set; }
}

My Model has [Required] validation on the name property and when I put debugger on my controller, it recognizes that the ModelState is not valid and returns back to the view but I do not see any errors on my page. I may be missing something very trivial since this is my first time using MVC's validation framework.

One thing I would like to add is that I am calling Controller with an Ajax Post Can that be contributing to this anomaly?

Upvotes: 1

Views: 108

Answers (2)

Andi AR
Andi AR

Reputation: 2918

Try this ,

Add model error in your action

 ModelState.AddModelError("keyName","Error Message");

Use this to display in view

  @Html.ValidationMessage("keyName")

Upvotes: 0

rustem
rustem

Reputation: 153

<td>@Html.ValidationMessageFor(m => m.Name, "Name is required")</td>

This helper method generates a span with attribute below:

data-valmsg-replace="false"

Means that you'll see a static error message below your field, but you'll not be able to change that field with your Error Message defined in Model. Again, you'll see some static error message under your field. if @stephen muecke's solution works, means that your problem wasn't about adding ErrorMessage to wrong place. The only difference I see between your code and @stephen's answer is

return View("New",application);

changed to

return View(application);

This means that maybe you were returning the wrong view from your Action.

Upvotes: 1

Related Questions