2015-05-09 76 views
2

我有這樣的問題。在RouteConfig.cs,我設定的路線asp.net mvc - 返回視圖後重寫網址

routes.MapRoute(
     "NewsDetails", 
     "news/details-news/{title}-{id}", 
     new { controller = "News", action = "Details", id = "", title = "" } 
); 

在我NewsController的Index.cshtml我有一個鏈接

@Html.RouteLink(item.Title, "NewsDetails", new { 
     title = MyWeb.Classes.PrettyUrlHelper.PrettyUrl(item.Title), 
     id = item.Id 
}) 

在我NewsController:

public ActionResult Details(string title,String id) 
{ 
    if (id == null && title == null) 
     return RedirectToAction("Index"); 


    try 
    { 
     int ID = Int32.Parse(id); 

     var result = NewsConnectionDB.GetInstance().Single<LifeStory>(ID); 

     return View(result); 
     } 

     catch (InvalidOperationException) { 
      return View("~/Views/Error/Error404.cshtml"); 
     } 
     catch (FormatException) { 
      return View("~/Views/Error/Error404.cshtml"); } 
} 

因此,如果用戶點擊在鏈接中查看,該鏈接將路由到動作細節處理,並且鏈接是Seo Url Friendly(localhost:9224/news/details-news/ten-things-2)。但用戶鍵入的鏈接,而不是點擊鏈接在查看:

localhost:9224/news/details-news/ten-thingsblahblahblah-2 

上面的網址是正確的id但標題不是。那麼,如何在我返回後更新網址,如果用戶鍵入錯誤的標題,但正確的ID?

任何幫助,將不勝感激。

P/S:我的英文不好,所以希望你能理解。

+0

在控制器,具有代碼重寫這個URL ** HttpContext.Current.Response。 AppendHeader(「CorrectUrl」,「YourUrl」); ** – HoangHieu

回答

0

如果標題不正確,則可以在響應標題中發送正確的網址。如果是ajax調用,則在完成時檢查響應頭中的正確url。如果存在正確的網址,請使用window.history.pushState JavaScript方法更改瀏覽器網址。

詳細信息操作方法使用下面的代碼來設置響應頭。

HttpContext.Current.Response.AppendHeader("CorrectUrl", "YourUrl"); 
+0

它沒有工作,我試試HttpContext.Response.Headers.Add(「Content-Length」,String.Format(「/ news/details-news/{ 0} - {1}「,result.Title,result.Id));但一切都不會發生。如果我嘗試返回重定向(字符串。格式(「/新聞/詳細信息 - 新聞/ {0} - {1}」」,result.Title,result.Id));這將重新查詢數據庫再次,這不是好做的方式,我說的對? –

0

使用HttpServerUtility.UrlEncode(串);

javascript代碼可以替換url,我認爲它會工作:)。

C#代碼

string _entitle = HttpServerUtility.UrlEncode(_strTitle); 
string _strCorUrl = "http://example.com/"+ _entitle + "-" + _intID.toString(); 

腳本代碼

top.window.location.replace('CorrectUrl'); 

或C#代碼重定向URL

Response.Redirect(url); 

更新 可以1種溶液Context.RewritePath

https://msdn.microsoft.com/en-us/library/sa5wkk6d(v=vs.110).aspx

void Application_BeginRequest(Object sender, EventArgs e) 
{ 
    string originalPath = HttpContext.Current.Request.Path.ToLower(); 
    if (originalPath.Contains("/page1")) 
    { 
     Context.RewritePath(originalPath.Replace("/page1", "/RewritePath.aspx?page=page1")); 
    } 
    if (originalPath.Contains("/page2")) 
    { 
     Context.RewritePath(originalPath.Replace("/page2", "/RewritePath.aspx"), "pathinfo", "page=page2"); 
    } 
} 

它的代碼是例如,你可以用它 我希望它幫

+0

感謝您的幫助,腳本代碼不工作,但C#重定向URL一樣。如果我使用重定向將重定向行動的細節再次所以我必須再次重新查詢數據庫,就是這樣幹好辦法嗎? –

+0

檢查我的更新回答 – HoangHieu

+0

我嘗試更新您的答案,但它並沒有任何事情發生,所以我必須使用重定向方法和一些靜態變量防止再次重新查詢數據庫。感謝您的幫助和支持我。 –