我使用这样的导航:
<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');
并确保您不preventDefault
或return 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/