问题描述:

In MVC2, if I had a textbox and a submit button (hooked to a javascript/ajax call) within a form, pressing the enter key would automatically fire the submit button's javascript method. In MVC3 Razor however, pressing the enter key posts the form normally rather than doing an Ajax Request. Any reason for the difference between MVC2 and Razor?

EDIT: Basically what happens when I hit enter is that I get the File Save As dialog, and when I save the file and open it, the contents of the file has the response string.

网友答案:

If you are using any of the Ajax.* helpers (such as Ajax.BeginForm, or Ajax.ActionLink) you need to remove all Microsoft*.js scripts and replace them with: jquery.unobtrusive-ajax.js, like this:

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

The reason is that staring from ASP.NET MVC 3 Microsoft realized that reinventing the wheel is never a good thing and deprecated their MsAjax script libraries in favor to the far more advanced and better jQuery library. So those scripts are no longer used (they are just provided for backwards compatibility). ASP.NET MVC 3 Ajax.* helpers use HTML5 data-* attributes which are unobtrusively AJAXified with jQuery.

Also you should ensure that unobtrusive AJAX is enabled in your web.config:

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

If you still want backwards compatibility or something you could set the UnobtrusiveJavaScriptEnabled property to false and this will fallback to the previous Microsoft*.js libraries (absolutely not recommended).

And the same stands for client side javascript validation: the jquery.validate plugin is used by default with unobtrusive HTML5 data-* attributes generated on the input fields.

相关阅读:
Top