发布数据时维护ViewBag值 [英] Maintaining ViewBag values while posting data

查看:82
本文介绍了发布数据时维护ViewBag值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a logical question that needs to be answered!!

这是一个场景.

-输入控制器

ViewBag.Name = "aaaa";

-在视图中

-In View

@ViewBag.Name

在我的控制器中,我为ViewBag设置了值,并在VIew中从ViewBag检索了值.现在在View中,我有一个按钮,该按钮将一些数据发布到HttpPost方法中.在HttpPost方法中,我更改了值对于ViewBag.因此,执行该方法后,对于当前视图,viewbag中的值将更改还是不更改?"

"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方法中

-In HttpPost Method

ViewBag.Name="bbbb";

推荐答案

您在操作方法上设置的ViewBag数据仅对您正在使用的即时视图可用.除非将其保存在表单内的隐藏变量中,否则它将不可用.这意味着,在HttpPost操作方法中更改ViewBag数据后,您可以在返回的视图中看到

The ViewBag data you set on an action method will be available only to the immediate view which you are using. It will not be availabe when you post it back to your server unless you keep that in a hidden variable inside the form. That means, after you change your ViewBag data in your HttpPost action method, you can see that in the view you are returning

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数据

Assuming your view is printing the ViewBag data

<h2>@ViewBag.Message</h2>
@using(Html.BeginForm())
{
  <input type="submit" />
}

结果将是

对于您的GET Aciton,它将打印"From GET"

For your GET Aciton, It will print "From GET"

用户提交表单后,将显示"Totally new value";

After user submit's the form, It will print "Totally new value";

如果要发布以前的查看包数据,请将其保留在隐藏的表单字段中.

If you want the previous view bag data to be posted, keep that in a hidden form field.

<h2>@ViewBag.Message</h2>
@using(Html.BeginForm())
{
  <input type="hidden" value="@ViewBag.Message" name="Message" />
  <input type="submit" />
}

还有您的Action方法,我们也将接受隐藏字段值

And your Action method, we will accept the hidden field value as well

[HttpPost]
public ActionResult Create(string someParamName,string Message)
{
  ViewBag.Message = ViewBag.Message + "- Totally new value";
  return View();
}

结果将

对于您的GET Aciton,它将打印"From GET"

For your GET Aciton, It will print "From GET"

用户提交表单后,将打印"From GET-Totally new value";

After user submit's the form, It will print "From GET-Totally new value";

尽量避免使用动态内容(例如ViewBag/ViewData)在操作方法和视图之间传输数据.您应该使用强类型视图和视图模型.

Try to avoid dynamic stuff like ViewBag/ViewData for transferring data between your action methods and views. You should use strongly typed views and viewmodels models.

这篇关于发布数据时维护ViewBag值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆