Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery unobtrusive

I'm trying to include the unobtrusive.js to my mvc3 view, but when I do, I get a bunch of errors when the view renders. The exception is in the unobtrusive script, anywhere where it checks anything against 'undefined' like this line here

if(message !== undefined) //Compare against undefined, because an empty message is legal

The error I'm getting is

Microsoft JScript runtime error: 'undefined' is null or not an object

Here is my script declaration for my view.

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.14.custom.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<link href="@Url.Content("~/Content/themes/base/jquery.ui.autocomplete.css")" rel="stylesheet" type="text/css" /> 
like image 894
Jeff Reddy Avatar asked Dec 02 '22 02:12

Jeff Reddy


2 Answers

You need to use jquery.validate.min.js instead of jquery.validate.unobtrusive.js

like image 178
Brandon Avatar answered Dec 10 '22 00:12

Brandon


If you want to:

  • Use .NET model validation (data annotations attributes)
  • Use html5 data attributes instead of non semantic css classses

You need both: jquery.validate AND jquery.validate.unobtrusive

Script References:

Note: In this example the js files are located under "public" folder in the project/site but you use Microsoft of Google CDN addresses if possible.

<script src="@Url.Content("~/public/js/libs/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/public/js/libs/jquery.validate.unobtrusive.min.js")"></script>

Model:

public class PimpModel
{
  [Required]
  [StringLength(20)]
  [DisplayName("Pimp Name")]
  public string PimpName { get; set; }
}

Web.config Settings

 <appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

View Form Code

@model SomeProject.Models.PimpModel
@{
  View.Title = "Index";
  Layout = "~/Views/Shared/_Layout.cshtml";
  Html.EnableUnobtrusiveJavaScript(true);
}
<h2>Pimp</h2>
@using (Html.BeginForm()) {
  @Html.ValidationSummary(true)
  <fieldset>
  @Html.ValidationMessageFor(model => model.PimpName)
  <div class="editor-label">
    @Html.LabelFor(model => model.PimpName)
  </div>
  <div class="editor-field">
    @Html.TextBoxFor(model => model.PimpName)
  </div>
  <input type="submit" value="Save"></fieldset>
}

The html helpers generate data attributes in the form html that are used by the unobtrusive library, the unobtrusive library uses functions in the validation library and it's all happy days...

like image 39
Steven Quick Avatar answered Dec 09 '22 22:12

Steven Quick