JustJohn
JustJohn

Reputation: 1460

Validation fires but doesn't show message on failure. What am I missing? MVC 5 Razor

I can't seem to get the Validation error messages to show under the input model fields on the View.

The [Required] tag above Description input makes the ModelState Invalid, but doesn't stop the submission. I have to catch it with checking the Model State. Am I missing some .js files? I dont' have any examples to doublecheck this.

Here is my model (notice I have only one [Required] for now):

public partial class Requests
{
    public int RequestID { get; set; }
    public string NickName { get; set; }
    public Nullable<double> Lat { get; set; }
    public Nullable<double> Lng { get; set; }
    public string ZipCode { get; set; }
    [Required(ErrorMessage = "Description of what you need is missing.")]
    public string Description { get; set; }
    public System.DateTime DateCreated { get; set; }
}

Here is my View where the Description input needs input.

<div class="form-group">
    @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", @rows = "20", @cols = "200" } })
        @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
    </div>
</div>

Here is my controller ActionResult (skinnied down)

if (ModelState.IsValid)
{
 //THIS ALL WORKS IF Description HAS INPUT

}
else
{
  TempData["Saved"] = "Nothing saved yet. Look for reason.";
return RedirectToAction("StoreRequests", new { lat = requests.Lat, lng = requests.Lng });
}

On ModelState failure the user is directed to the correct View and TempData shows that nothing was saved. However, there is no error message on the View below the offending input, no ValidationSummary at the top of the view, and submission is not stopped on input mistake.

@if(TempData["Saved"] != null)
{
    <span style="color: red;">@TempData["Saved"].ToString()</span>
}
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })

Upvotes: 0

Views: 881

Answers (2)

itzmebibin
itzmebibin

Reputation: 9439

Include the following necessary scripts directly in your .cshtml file.

<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

Upvotes: 0

user3559349
user3559349

Reputation:

In order to get client side validation (and therefore prevent the form being submitted if its invalid), you need to include the following scripts in you view (or layout).

jquery-{version}.js
jquery.validate.js
jquer.validate.unobtrusive.js

If you have the default bundles set up by VS when you create a new project, you can simply add the following to the view

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

In addition, you should not be redirecting if ModelState is invalid, but rather returning the current view, which will display any validation errors even if the user has disabled javascript. By redirecting, your lose current ModelState so no validation errors will be displayed in the view your redirecting to, not to mention that any data the user previously filled (except the 2 parameters your passing) will be lost.

public ActionResult Edit (Requests model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    // save you data and redirect
}

Upvotes: 1

Related Questions