How can ViewBag data be saved after a form post?

2019-04-25 02:44发布

问题:

So I have a ViewBag.Something and this data is randomly generated. In my view, I set this to a label like so @Html.LabelFor(m => m.Something, (string)ViewBag.Something). This works out well but when I submit the form there could be errors and if there are errors, I need this label to remain the same, I don't want dynamic/random data anymore so I wouldn't call the controller method that generated this ViewBag. Is there a way to retain this value without having some private variable in my controller? Some nice way that MVC/Razor does it?

回答1:

Option 1:

Pass the value of "ViewBag.Something" to the Controller by using route Values:

@Html.ActionLink("ButtonText", "ActionName", new { Something = @ViewBag.Something })

Option 2: You can use TempData.

public ActionResult Index()
{
 var Something = "YOURVALUE";
 TempData["Something"] = Something;
.......
}


public ActionResult OtherAction()
{
    var Something = TempData["Something "];
    ...........
}

Passing State Between Action Methods

Action methods might have to pass data to another action, such as if an error occurs when a form is being posted, or if the method must redirect to additional methods, as might occur when the user is directed to a login view and then back to the original action method.

An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.



回答2:

In the get, set up a model, set it dynamically and when return view() is being executed, do return view(model). Then in the view, set up a hidden field that can keep on passing the value needed. I chose to go this route because I don't have to worry about any server code to make this work on a post and I don't have to worry about any sessions.



回答3:

Displaying message in viewbag after posting (I user this method)

ActionResult SubmitUser(){

  ViewBag.Msg =TempData["Msg"];

  return view();
}


[HtttpPost]
ActionResult SubmitUser(){

 TempData["Msg"] ="Submitted Successfully"];

  return view();
}

The Value is send to get method..