MVC5 - Data Annotations - Client Side Validation Does Not Occur?

I have an MVC 5 application and I use data annotations to do most of the validation. One of the properties of my class is as follows:

[Required(ErrorMessage = "Please enter a business name")] [StringLength(80)] public string BusinessName { get; set; } 

Validation works, but it doesn't seem to work in the browser as I thought. There is a Save button on my page. If I left the business field field blank and click "Save", a message will be made for the controller method, which partially looks like this:

  [HttpPost] public ActionResult Create(Advertiser advertiser, FormCollection collection, HttpPostedFileBase file) { // Before we do anything, let check to make sure any validation that already been done is clean. if (!ModelState.IsValid) { return View(advertiser); } ... ... } 

When this method is executed, the state of the model is already set to invalid. This is good because it is not true because the Business Name field is empty. However, should this not be checked on the client?

The field in my .cshtml file looks like this (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 installed 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> 
+7
asp.net-mvc asp.net-mvc-4 data-annotations
source share
1 answer

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 I did not understand that the jqueryval package is NOT loaded into the _Layout.cshtml file by default. Therefore, I needed to add it as follows:

 @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) 

As soon as I did this, it works as it should. Of course, this will make it load for all pages. This may be undesirable. If not, download it separately on each page as needed.

+10
source share

All Articles