javascript - 在 asp.net mvc 应用程序中使用 href 属性进行重定向不起作用

标签 javascript jquery asp.net asp.net-mvc url

我使用这样的导航:

<a href="/MyMessages/?messageId=1"> First message </>

但在导航用户之前,我会在 JavaScript 中处理该事件:

$('a').on('click', function (event) {
    event.preventDefault();
    // Do stuff
    // Navigate:
    location.pathname = $(this).attr('href'); // href is /MyMessages/?messageId=1
});

但是它在浏览器中被编码,地址是:

localhost:52500/MyMessages/%3FmessageId=1

并且mvc路由失败:

Server Error in '/' Application.

A potentially dangerous Request.Path value was detected from the client (?).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: A potentially dangerous Request.Path value was detected from the client (?).

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (?).]
System.Web.HttpRequest.ValidateInputIfRequiredByConfig() +9807692
System.Web.PipelineStepManager.ValidateHelper(HttpContext context) +53

但是当我只是通过深度链接进行导航时

localhost:52500/MyMessages/?messageId=1

一切正常。

如何避免浏览器对我的网址进行编码并防止出现错误?

最佳答案

如果您在事件处理程序中执行的最后一件事是转到确切的 href,则删除:-

location.pathname = $(this).attr('href');

并确保您不preventDefaultreturn false;

在点击事件后,浏览器将正常使用 href 重定向到 anchor

User can also choose to stay on the page (popup has yes/no buttons, after preventing default if its dirty), and then if he chooses to navigate again, the same would happen

尝试类似:-

$('a').on('click', function (event) {
    if(dirty){
       event.preventDefault();
       $('#yes').attr('href', $(this).attr('href'));
       $('#popup').show();
    }
});

并创建#yes作为 anchor 。

关于javascript - 在 asp.net mvc 应用程序中使用 href 属性进行重定向不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791059/

相关文章:

javascript - 基于 observable,从 observable 对象中选择 observable

javascript - Jquery 停止第一个单击的按钮执行相同的代码

javascript - 当指针位于页面右侧时自动重新对齐工具提示

asp.net - Paypal IPN 中缺少自定义值

c# - 如何阻止 GridView 中的特定列

javascript - 中型设备的设计突破

javascript - 等待不在 Tensorflow.js 的 model.fit 上工作

javascript - 将字符串作为参数传递给 gulp 任务

转发器错误中的 C# ASP.NET 更新面板

Jquery启用和禁用dom元素而不删除