2010-12-06 94 views
23

我想發佈一些關於ASP.Net MVC的問題。我對Web開發並不熟悉,但我被分配到了項目的Web部分。我們正在做以下幾點:第一,我們創建了個人數據get & set性質:在asp.net中使用RedirectToAction mvc

public class Person 
{ 
    public int personID {get;set;} 
    public string personName {get;set;} 
    public string nric {get;set;} 
} 

,並登錄後,我們把數據放在一個類Person對象,我們使用RedirectToAction這樣的:

return RedirectToAction("profile","person",new { personID = Person.personID}); 

工作正常,但參數顯示在URL中。我怎樣才能隱藏它們,也可以隱藏動作名稱?請給我一些例子的正確方法。

+3

請停止在您的主題行中使用感嘆號!!!! – 2010-12-22 03:21:01

+4

請停止使用一般的感嘆號,如評論。 – 2013-04-03 18:18:05

+2

請刪除鍵盤上包含感嘆號的鍵,並鼓勵其他人這樣做,以便從互聯網上刪除這個可怕的病毒:) – MikeD 2014-01-14 13:30:48

回答

34

該參數顯示在URL中,因爲這是RedirectToAction的第三個參數 - 路由值。

缺省路由是{controller}/{action}/{id}

所以這個代碼:

return RedirectToAction("profile","person",new { personID = Person.personID}); 

將產生以下網址/路徑:

/人/資料/ 123

如果您想要一個更清潔的路線,像這樣(例如):

/人/ 123

創建一個新的路線:

routes.MapRoute("PersonCleanRoute", 
       "people/{id}", 
       new {controller = "Person", action = "Profile"}); 

以及您的網址應該是乾淨的,像上面。

或者,您可能根本不喜歡使用ID,您可以使用其他一些唯一標識符 - 如暱稱。

所以URL可以是這樣的:

人/ rpm1984

爲了做到這一點,只是改變你的路線:

routes.MapRoute("PersonCleanRoute", 
        "people/{nickname}", 
        new {controller = "Person", action = "Profile"}); 

而且你的操作方法:

public ActionResult Profile(string nickname) 
{ 

} 

而你的RedirectToAction代碼:

return RedirectToAction("profile","person",new { nickname = Person.nickname}); 

這是你的事後?

8

如果您不希望參數顯示在地址欄中,您需要將其保存在重定向之間的服務器上的某個位置。實現這個目標的好地方是TempData。這裏有一個例子:

public ActionResult Index() 
{ 
    TempData["nickname"] = Person.nickname; 
    return RedirectToAction("profile", "person"); 
} 

現在的剖面行動要重定向從TempData取,

public ActionResult Profile() 
{ 
    var nickname = TempData["nickname"] as string; 
    if (nickname == null) 
    { 
     // nickname was not found in TempData. 
     // this usually means that the user directly 
     // navigated to /person/profile without passing 
     // through the other action which would store 
     // the nickname in TempData 
     throw new HttpException(404); 
    } 
    return View(); 
} 

在幕後TempData使用Session用於存儲,但它會重定向後會自動驅逐,所以這個值只能用於你需要的一次:store,redirect,fetch。

1

這可能是問題的解決方案時,TempData的去刷新頁面後: -

第一,當你到達TempData的行動方法對其進行設置在下面一ViewData的&寫檢查:

public ActionResult Index() 
{ 
    TempData["nickname"] = Person.nickname; 
    return RedirectToAction("profile", "person"); 
} 

現在在配置文件操作:

public ActionResult Profile() 
{ 
    var nickname = TempData["nickname"] as string; 

if(nickname !=null) 
ViewData["nickname"]=nickname ; 

if (nickname == null && ViewData["nickname"]==null) 
    { 
    throw new HttpException(404); 
    } 
else 
{ 
if(nickname == null) 
nickname=ViewData["nickname"]; 
} 
    return View(); 
} 
相關問題