我在我的控制器中有一個動作如下。如何解決動作參數類型不匹配?
//
// GET: /HostingAgr/Details/1
public ActionResult Details(int id)
{
HostingAgreement hosting = hmEntity.HostingAgreements.SingleOrDefault(h => h.AgreementId == id);
if (hosting == null)
{
TempData["ErrorMessage"] = "Invalid Agreement ID";
return RedirectToAction("Index");
}
return View(hosting);
}
現在,如果我把網址,如下所示。(用於測試目的)
/HostingAgr/Details/1fakeid
系統會拋出異常。
參數字典包含參數 非空類型「System.Int32」的方法 「System.Web.Mvc.ActionResult詳細信息(的Int32)」在 「HostingManager的「ID」一個空條目。 Controllers.HostingAgrController」。可選 參數必須是參考類型,可爲空類型,或者聲明爲可選參數 。參數名稱:參數
因爲id在URL參數中變成了字符串。我如何處理這種情況而不會引發系統錯誤?
由於您正在討論操作而不是結果,因此從標題中刪除了「ActionResult」。 – jgauffin 2012-02-29 09:49:07