我正在撰寫我的第一個 MVC 應用程式。在創建打開詳細資訊視圖的鏈接時,我必須傳遞 id。
在 Controller 方法中,如下所示:
public ActionResult getDetails(int UserMasetrId)
{
...Some Code
}
在 VIEW 鏈接中生成如下:
<a title="View Details" href="@Url.Action("getDetails", "UserMaster", new {id=item.UserMasterId})"></a>
對于上面的代碼鏈接生成為...controllername/getDetails/13616. 但它會引發錯誤:
“引數字典包含“APP.Controllers.UserMasterController”中方法“System.Web.Mvc.ActionResult getDetails(Int32)”的不可為空型別“System.Int32”的引數“UserMasterId”的空條目。可選引數必須是參考型別、可空型別或宣告為可選引數。”
現在,如果我如下更改操作鏈接?
<a title="View Details" href="@Url.Action("getDetails", "UserMaster", new {UserMasterId=item.UserMasterId})"></a>
它作業正常,但鏈接更改為 ...controllername/getDetails?UserMasterId=13616
因此,請在我在操作方法中撰寫引數名稱時提出任何解決方案,并且我希望 url 的格式不顯示引數名稱意味著 url 的格式應該conrtoller/actionmethod/parametervalue。
uj5u.com熱心網友回復:
函式中的引數名稱應與按鈕鏈接中的查詢引數匹配。
<a title="View Details" href="@Url.Action("getDetails", "UserMaster", new { UserMasterId = item.UserMasterId})"></a>
如果您不使用默認Id引數,您還應該宣告一個 Route。
[Route("ControllerName/getDetails/{UserMasterId}")]
public ActionResult getDetails(int? UserMasterId)
{
if (id == null)
{
return NotFound();
}
}
uj5u.com熱心網友回復:
您使用的不是ActionLink. 您正在為您的href操作生成一個鏈接。a您可以使用 HtmlHelper生成正確的標簽:Html.ActionLink像這樣:
Html.ActionLink("", "getDetails", "UserMaster", new { item.UserMasterId }, null)
這將生成這樣的錨標記,假設item.UserMasterId為 1:
<a href="/UserMaster/getDetails/1"></a>
并將您的Controller方法更改為:
public ActionResult getDetails(int? id)
{
...Some Code
}
uj5u.com熱心網友回復:
如果您剛開始學習 MVC,最好以正確的方式學習它。您應該使用 Route 引數,而不是 QueryString 引數。所以保持你的鏈接不變
<a title="View Details" href="@Url.Action("getDetails", "UserMaster", new {id=item.UserMasterId})"></a>
但是修復動作,你的動作不是MVC風格,應該是
[Route("{userMasterId?}")]
public ActionResult getDetails(int? userMasterId)
{
...Some Code
}
但是名稱無關緊要,重要的是路由引數和動作引數名稱應該相同,您也可以使用它
[Route("{id?}")]
public ActionResult getDetails(int? id)
{
...Some Code
}
uj5u.com熱心網友回復:
從所有建議中并在實施這些建議后,我決定在鏈接和操作方法引數名稱中,如果您使用與默認路由器中建議的相同引數名稱,則 URL 將生成,
ControllerName/actionMthod/value
并且在所有其他情況下它將生成ControllerName/actionMthod?ParamerName=value.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/441300.html
標籤:C# asp.net-mvc 路线 控制器 动作链接
上一篇:關于將物體保存到資料庫的問題
下一篇:未找到視圖“索引”,但它確實存在
