发布数据时维护 ViewBag 值

Maintaining ViewBag values while posting data

我有一个逻辑问题需要回答!!

这是一个场景..

-在控制器中

ViewBag.Name = "aaaa";

-在视图中

@ViewBag.Name

"In my controller, i have set value for ViewBag and retrieved value from ViewBag in VIew. Now in View, i have a button, which is posting some data to a HttpPost method. In HttpPost method, i have changed the values for ViewBag. So after the execution of that method, the values in the viewbag will change or not for current view??"

-在 HttpPost 方法中

ViewBag.Name="bbbb";

ViewBag 无法在请求中存活。 post 之后唯一存在的数据是您 post 编辑的数据,不包括 ViewBag。不确定你的问题是什么。

您在操作方法上设置的 ViewBag 数据将仅对您正在使用的即时视图可用。当您 post 将它返回到您的服务器时,它将不可用,除非您将其保存在表单内的隐藏变量中。这意味着,在 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”;

如果您希望post编辑之前查看的行李数据,请将其保存在隐藏的表单字段中。

<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 这样的动态内容在您的操作方法和视图之间传输数据。您应该使用强类型视图和视图模型模型。