1
votes

I have a form in a view and I pass some information to the Controller through a Submit button. In the controller, in an ActionResult called SaveP I want to verify some conditions and to pass the result of these validations back to the view, so that it display something when the page is reloaded after pressing the submit button.

The code is something like that:

 if (!(editor.ID != null && !string.IsNullOrEmpty(editor.Number) && (!ext.SID.HasValue)))
                {
                    _db.M.DeleteM(editor.PID);
                    pa.P.MID = null;
                    TempData["m"] = false; 

I want the view to display some things only if these conditions apply. Also, this action result called SaveP redirects to return RedirectToAction("P", new { id = editor.ID });

I have used ViewBag and it didn't work, but then I found out that ViewBag elements don't preserve after a redirect. Then, I tried with a TempData, but it is null in the view. How should I solve this? thanks!

2
Create yourself a model and add a new property to it? - Canvas
How have you accessed the TempData value in the GET method you redirect to? You need to show the relevant code. But if all you want to do is pass a bool value then just add a parameter to your method and use RedirectToAction("P", new { id = editor.ID, myBool = false }) - user3559349
TempData only persists between controller actions (eg redirects) and you can only access them once. The action, you redirect to, can add the value of your TempData to the ViewBag. - Silvermind

2 Answers

1
votes
RedirectToAction("P", new { id = editor.ID ,check = true});

and P action will be like

public ActionResult P(int id,bool check=false)
{ 
  viewBag.check = check;
}

if you pass check = true you will get true in check in P action and if you dont pass any thing then dont wory its value will set to false. so if this method is call from multiple location and you didnot pass check parameter then will not throw error...

0
votes

That's where Model comes. You can send the value in a property using a model object from controller to View. In you view using HTML Helpers bind this model property with the element you desire. In your post action create a parameter of this model's object. It will be filled with properties when the model is posted back from view.