2017-04-25 73 views
0

初學者問題 - 我有一個HomeController,HomeModel和HomeView。當用戶訪問http://page/Home頁面時,將執行Index方法,他可以填寫一些控件。在他點擊一個按鈕(回發)後,將執行處理操作,如果發生錯誤,應用程序將調用ModelState.AddModelError方法。然後再次調用Index操作,我可以在頁面上顯示錯誤。如何在返回新視圖時保留網址

這工作正常,但問題是,回發後的新url是http://page/Home/Index而不是http://page/Home。任何想法如何防止這一點?

PS - 我想this解決方案,但隨後新的URL是像http://page/Home?...long string of serialized ModelState data...

我的控制器:

[HttpGet] 
public ActionResult Index(MyModel model) 
{ 
    return View(model); 
} 

[HttpPost] 
public ActionResult Process(MyModel model) 
{ 
    if (...error...) 
    { 
     model.SetErrorState(); 
     ModelState.AddModelError("ProcessError", "error message"); 
     return View("Index", model); 
    } 
    else 
    { 
     // do something... 
     model.SetSuccessState(); 
     return View("Index", model); 
    } 
} 

回答

2

的問題是你推到一個新的URL爲HttpPost行動。如果將此更改爲您的Home操作的HttpPost版本,則可以整齊地返回到頁面,而不會錯誤地更改URL。

例如

[HttpGet] 
public ActionResult Index(ImportData model) 
{ 
    return View(model); 
} 

[HttpPost] 
public ActionResult Index(MyModel model, FormCollection data) 
{ 
    if (...error...) 
    { 
     model.SetErrorState(); 
     ModelState.AddModelError("ProcessError", "error message"); 
     return View(model); 
    } 
    else 
    { 
     // do something... 
     model.SetSuccessState(); 
     return View(model); 
    } 
} 
+0

我在我的問題中犯了一個錯誤 - 兩種方法都期望一個參數具有相同類型'MyModel'。如果我糾正這個問題並應用你的解決方案,那麼編譯器會抱怨'類型HomeController已經定義了一個名爲Index的成員,它具有相同的參數類型'。 – sventevit

+0

更新@sventevit :)只需添加(未使用)'FormCollection' var來區分。 – scgough

+0

完美,謝謝:) – sventevit

相關問題