2016-03-04 31 views
1

我用導航這樣的:重定向使用asp.net MVC應用程序的href屬性不工作

<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

但當我只是deeplinking像

localhost:52500/MyMessages/?messageId=1 

一切正常瀏覽。

如何避免我的瀏覽器編碼我的網址,並防止我得到的錯誤?

回答

0

,如果你在你的事件處理程序做的最後一件事就是去準確的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爲錨。

+0

工作。但是,我的實現要求我阻止默認設置,以便瀏覽器不會生成彈出窗口。有沒有這樣的方式? – Mefhisto1

+0

生成彈出窗口?你能解釋一點嗎? – BenG

+0

我將窗體標記爲髒,並生成一個自定義彈出窗口,通知用戶在導航時未保存更改。併爲此工作(不顯示通用瀏覽器彈出),而是顯示我自己的自定義彈出我必須preventDefault。 – Mefhisto1

相關問題