Reputation: 48402
I have an MVC 5 app, and I'm using data annotations to do a majority of validation. One of the properties in my class looks like this:
[Required(ErrorMessage = "Please enter a business name")]
[StringLength(80)]
public string BusinessName { get; set; }
The validation is working but it doesn't appear to be happening in the browser like I thought it should. On my page I have a Save button. If I leave the Business Name field blank and click Save, a post is done to a controller method that looks, partially, as follows:
[HttpPost]
public ActionResult Create(Advertiser advertiser, FormCollection collection, HttpPostedFileBase file)
{
// Before we do anything, let's check to make sure any validation that's already been done is clean.
if (!ModelState.IsValid)
{
return View(advertiser);
}
...
...
}
When this method is executed, the model state is already set to invalid. That's good because it is invalid because the Business Name field is empty. However, shouldn't this validation be happening in the client?
The field in my .cshtml file looks as follows (using Bootstrap):
<div class="form-group">
@Html.Label("Business Name", new { @class = "control-label col-md-3" })
<div class="col-md-9">
@Html.TextBoxFor(model => model.BusinessName, new { @class = "form-control", title = "", autofocus = true })
@Html.ValidationMessageFor(model => model.BusinessName)
</div>
</div>
My Web.Config is set correctly as follows:
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Upvotes: 8
Views: 14589
Reputation: 48402
I found my problem. In my BundleConfig.cs I have the following:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.min.js",
"~/Scripts/jquery-ui-1.10.4.min.js",
"~/Scripts/jquery.base64.js"
));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate.min.js",
"~/Scripts/jquery.validate.unobtrusive.min.js"
));
But, what I didn't realize is that the jqueryval bundle DOES NOT get loaded in the _Layout.cshtml file by default. So I needed to add it, as follows:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
Once I did this, it is working as it should. Of course, this will cause it to get loaded for all pages. That may not be desirable. If not, load it separately in each page as necessary.
Upvotes: 14