Pregunta

My MVC app is generating the following HTML which causes a Javascript syntax error upon submission (I'm not typing anything into the two text boxes). Here's the generated HTML and the submit handler:

<form action="/UrIntake/Save" id="UrIntakeForm" method="post">

    <input data-val="true" data-val-length="The field LastName must be a string with a maximum length of 50." data-val-length-max="50" data-val-required="The LastName field is required." id="FormSubmitter_LastName" name="FormSubmitter.LastName" type="text" value="" />
    <input data-val="true" data-val-length="The field FirstName must be a string with a maximum length of 50." data-val-length-max="50" data-val-required="The FirstName field is required." id="FormSubmitter_FirstName" name="FormSubmitter.FirstName" type="text" value="" />

    <div id="SubmissionButtons" class="right">
            <input type="button" onclick="SubmitForm()" value="Submit" />
            <input type="button" onclick="CancelForm()" value="Cancel" />
    </div>
</form>

    function SubmitForm() {
        $("#UrIntakeForm").valid();
.
.
.

This is the jQuery code where the syntax error is occurring (v1.9.0). "data" is undefined and the "return" line is where the error occurs:

parseJSON: function( data ) {
    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        return window.JSON.parse( data );
    }

Presumably, I don't have to enter anything into the text boxes (and should then get the "field is required" message). Is this what's causing the error? That doesn't make sense, but I don't see what else it could be.

¿Fue útil?

Solución

Cause

This is an issue with jquery.validate.unobtrusive.js in your ASP.NET.MVC package.

As of jQuery 1.9, the behavior of parseJSON() has changed and an undefined value would be considered a malformed JSON, resulting in the error you've specified. See the jQuery 1.9 Core Upgrade Guide for more information.

Solution

Use the jQuery Migrate plugin, which among other things adds backward-compatibility to the jQuery parseJSON() utility.


EDIT

According to the official announcement in this thread on Microsoft Connect, the issue has been resolved in the latest release of the framework.

Naturally, as Andreas Larsen noted in the comments, make sure to clear any relevant cache, server-side and client-side, after upgrading to the new release.

Otros consejos

I also had this issue. The problem was that $.parseJSON(undefined) causes an exception to be thrown, and that the unobtrusive validation was making that call. As stated in the accepted answer, this has since been fixed.

You can download the Microsoft version of this script which will properly validate without causing an exception from this link: http://ajax.aspnetcdn.com/ajax/mvc/5.1/jquery.validate.unobtrusive.min.js

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top