2012-10-22 30 views
10

這裏就是我想要做的事:將模型對象傳遞給RedirectToAction而不污染URL?

public ActionResult Index() 
{ 
    return View(); 
} 

[HttpPost] 
public ActionResult Index(ContactModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // Send email using Model information. 

     return RedirectToAction("Gracias", model); 
    } 

    return View(model); 
} 

public ActionResult Gracias(ContactModel model) 
{ 
    return View(model); 
} 

這三種操作方法是在同一個控制器。基本上,用戶在聯繫表單中鍵入一些數據,我想用Model對象中的名稱將它們重定向到一個感謝頁面。

由於代碼是,它的工作原理,但URL與GET變量一起傳遞。不理想。

http://localhost:7807/Contacto/Gracias?Nombre=Sergio&Apellidos=Tapia&Correo=opiasdf&Telefono=oinqwef&Direccion=oinqef&Pais=oinqwef&Mensaje=oinqwef 

有什麼建議嗎?

回答

24

聽起來像是TempData的解決方案!

[HttpPost] 
public ActionResult Index(ContactModel model) 
{ 
    if (ModelState.IsValid) 
    { 
    // Send email using Model information. 
    TempData["model"] = model; 
    return RedirectToAction("Gracias"); 
    } 

    return View(model); 
} 

public ActionResult Gracias() 
{ 
    ContactModel model = (ContactModel)TempData["model"]; 
    return View(model); 
} 
+0

我不知道,你可以複雜類型保存到TempData的字典。 TIL。謝謝! – sergserg

+1

只要它們是可序列化的! TempData存儲在會話中,只允許Serializable對象/類。 –

+2

臨時數據當然可以在這裏工作,但爲什麼不直接從索引顯示「Gracias」視圖(模型已經在範圍內)。您還可以將自己保存爲一次實質上無用的重定向的服務器往返。 –

0

簡單的回答是不傳遞整個模型,但一些的標識,可以用它來檢索庫中的模型:

[HttpPost] 
public ActionResult Index(ContactModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // Send email using Model information. 

     return RedirectToAction("Gracias", model.ID); 
    } 

    return View(model); 
} 

public ActionResult Gracias(int contactID) 
{ 
    ContactModel model = new ContractRepository().GetContact(contactID); 
    return View(model); 
} 
+0

這不符合你的想法。如果我在'HttpPost Index()'方法中傳入更新後的模型,則所有這些更改都會丟失*,因爲方法'Gracias()'中的所有值都來自數據庫,而不是用戶。 –

0

而不是做

return RedirectToAction("Gracias", model); 

你可以做

[HttpPost] 
public ActionResult Index(ContactModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // Send email using Model information. 

     return View("Gracias", model); 
    } 

    return View(model); 
} 

並刪除您的Gracias控制器操作。使用上面的「Gracias」視圖將與您的ContactModel模型一起顯示。

如果使用相同的模型並且是工作流程的鎖定步驟部分,我看不到需要單獨控制器操作。 「一個成功的POST索引總是會導致顯示Gracias視圖」

您還可以將模型存儲在TempData中(這與1請求會話狀態相似),但是我沒有看到在此過程中有任何要點你的情況,因爲它只是使事情複雜化

想法?

+0

該網址看起來像'http:// localhost:7807/Contacto/Index',如果可以接受的話,這是最簡單的方法。 –

+0

是的,這是不可接受的,這就是爲什麼我沒有走這條路。 – sergserg

+0

現在只希望有人在其他時間點擊「http:// localhost:7807/Contacto/Gracias」(或者如果他們點擊後退按鈕並且頁面未被緩存),因爲會返回一個視圖有空字段,甚至可能是一個異常,這取決於你的視圖是什麼樣的。考慮到你可能不希望顯示另一個URL。 –

0

如果沒有重定向,這難道不能輕鬆完成嗎?

下面是我有:

[HttpGet] 
    public ActionResult Contact() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Contact(EmailResponse response) 
    { 
     if(ModelState.IsValid){ 
      return View("Thanks", response); 
     } 
     else 
     { 
      return View(); 
     } 
    } 

"Thanks"看法是強類型到EmailResponse