我對MVC非常陌生,並且試圖從爲MVC提供的視頻中學習。在其中一個視頻中,我使用了Tempdata。在視頻中,他們使用HTTPPOST顯示了創建的操作結果,並將數據從文本框傳遞到控制器,然後使用Tempdata進行查看。我曾嘗試過這樣做。但我沒有從文本框中獲得價值,總是返回null。下面是我的代碼,將文本框的值傳遞給MVC5中的ActionResult TempData
控制器如下,
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(string name)
{
TempData["uname"] =name;
return RedirectToAction("GetUser");
}
public ActionResult GetUser()
{
return View();
}
查看了創建如下,
@{
ViewBag.Title = "Create";
}
<h2>Create New User</h2>
@using (Html.BeginForm())
{
<div>
<p>Enter your name : <input type="text" id="id" placeholder="Enter username"/></p>
<p><input type="submit" id="btnSubmit" value="Create"/></p>
</div>
}
信息查看的getUser,
@{
ViewBag.Title = "GetUser";
}
<h2>GetUser</h2>
<div>
<h3>Welcome @TempData["uname"].ToString()</h3>
</div>
當我進入文本框的值並在「創建」操作中按下按鈕ID參數爲空。另外,我還沒有創建任何模型類,就像他們剛剛在上面顯示的代碼中一樣。請給我一些建議。
問候 桑傑塔
你剛纔錯過了你的文本框的name屬性。只需正確設置名稱屬性,使其與控制器的名稱參數相匹配即可。 NAME = 「名字」。 – drunkcoder
是的,它幫助.. – Sangeetha