我有一个逻辑问题需要回答!!
这是一个场景..
-在 Controller 中
ViewBag.Name = "aaaa";
-在 View 中
@ViewBag.Name
“在我的 Controller 中,我已经为 ViewBag 设置了值,并在 VIew 中从 ViewBag 检索了值。现在在 View 中,我有一个按钮,它正在将一些数据发布到 HttpPost 方法。在 HttpPost 方法中,我已经更改了值对于 ViewBag。那么在执行该方法后,viewbag 中的值对于当前 View 是否会更改???”
-在HttpPost方法中
ViewBag.Name="bbbb";
最佳答案
您在操作方法上设置的 ViewBag 数据将仅对您正在使用的即时 View 可用。当您将它发回您的服务器时,它将不可用,除非您将它保存在表单内的隐藏变量中。这意味着,在您在 HttpPost 操作方法中更改 ViewBag 数据后,您可以在返回的 View 中看到它
public ActionResult Create()
{
ViewBag.Message = "From GET";
return View();
}
[HttpPost]
public ActionResult Create(string someParamName)
{
ViewBag.Message = ViewBag.Message + "- Totally new value";
return View();
}
假设您的 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 这样的动态内容在操作方法和 View 之间传输数据。您应该使用强类型 View 和 View 模型模型。
关于c# - 发布数据时维护 ViewBag 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34223736/