您在操作方法上设置的 ViewBag 数据仅适用于您正在使用的即时视图。当您将其发送回服务器时,它将不可用,除非您将其保存在表单内的隐藏变量中。这意味着,在 HttpPost 操作方法中更改 ViewBag 数据后,您可以在返回的视图中看到该数据
public ActionResult Create()
{
ViewBag.Message = "From GET";
return View();
}
[HttpPost]
public ActionResult Create(string someParamName)
{
ViewBag.Message = ViewBag.Message + "- Totally new value";
return View();
}
假设您的视图正在打印 ViewBag 数据
<h2>@ViewBag.Message</h2>
@using(Html.BeginForm())
{
<input type="submit" />
}
结果将是
对于您的 GET Aciton,它将打印“From GET
"
用户提交表单后,它将打印“Totally new value
";
如果您希望发布以前的视图包数据,请将其保留在隐藏的表单字段中。
<h2>@ViewBag.Message</h2>
@using(Html.BeginForm())
{
<input type="hidden" value="@ViewBag.Message" name="Message" />
<input type="submit" />
}
对于您的 Action 方法,我们也将接受隐藏字段值
[HttpPost]
public ActionResult Create(string someParamName,string Message)
{
ViewBag.Message = ViewBag.Message + "- Totally new value";
return View();
}
结果将是
对于您的 GET Aciton,它将打印“From GET
"
用户提交表单后,它将打印“From GET-Totally new value
";
尽量避免像 ViewBag/ViewData 这样的动态东西在操作方法和视图之间传输数据。您应该使用强类型视图和 viewmodels 模型。