Asp.net-Mvc

在不顯眼的驗證期間 parseJSON 的語法錯誤

  • September 23, 2014

我的 MVC 應用程序正在生成以下 HTML,這會在送出時導致 Javascript 語法錯誤(我沒有在兩個文本框中輸入任何內容)。這是生成的 HTML 和送出處理程序:

<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();
.
.
.

這是發生語法錯誤的 jQuery 程式碼 (v1.9.0)。“數據”未定義,“返回”行是發生錯誤的地方:

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

據推測,我不必在文本框中輸入任何內容(然後應該得到“必填欄位”消息)。這是導致錯誤的原因嗎?這沒有意義,但我看不出還有什麼可能。

原因

jquery.validate.unobtrusive.js這是ASP.NET.MVC 包中的一個問題。

從 jQuery 1.9 開始, 的行為發生parseJSON()了變化,一個undefined值將被視為格式錯誤的 JSON,從而導致您指定的錯誤。有關更多資訊,請參閱jQuery 1.9 核心升級指南

解決方案

使用jQuery Migrate 外掛,其中包括向 jQueryparseJSON()實用程序添加向後兼容性。


編輯

根據Microsoft Connect 上此執行緒中的官方公告,該問題已在最新版本的框架中得到解決

當然,正如 Andreas Larsen 在評論中指出的那樣,確保在升級到新版本後清除任何相關的記憶體、伺服器端和客戶端。

引用自:https://stackoverflow.com/questions/14822540