2016-04-28 34 views
0

我有一個MVC控制器:MVC - 避免「參數字典包含參數無效項」

public ActionResult EditProduct(int id) 
    { 
     var model = products.GetById(id); 

     return View(model); 
    } 

    [HttpPost] 
    public ActionResult EditProduct(Product product) 
    { 
     products.Update(product); 
     products.Commit(); 

     return RedirectToAction("ProductList"); 
    } 

,當我做到這一點http://localhost:56339/Admin/EditProduct沒有在ID通過這樣http://localhost:56339/Admin/EditProduct/1,我會得到錯誤參數字典包含參數的空項。

如果用戶在沒有ID的情況下在URL中輸入,我該如何防止?

+3

你可以讓它爲空 - 「int? id' - 並重定向到另一個錯誤頁面,如果它沒有值。 –

+0

我同意@StephenMuecke,或者你也可以自動擁有與id相關的默認值。我想我們需要知道你想在這種情況下發生什麼。 –

+0

這樣做,我只是想重定向到另一個頁面。謝謝你們! –

回答

1

來自Stephen Muecke:你可以讓它爲空 - int? id - 並且如果它沒有值,則重定向到另一個錯誤頁面。

2

可以從兩個途徑實現這一目標:設置

1)設置空類型參數

public ActionResult EditProduct(int? id) 
    { 
if (id == null) 
      { 
     // nullable logic here 
      } 
      else { 
      // your logic here 
      } 
     return View(); 
    } 

2)可選參數

public ActionResult EditProduct(int id=0) 
     { 
    if (id == 0) 
       { 
      // nullable logic here 
       } 
       else { 
       // your logic here 
       } 
      return View(); 
     } 

希望它會幫助你。

相關問題