Elena E
Elena E

Reputation: 85

ASP.NET MVC ViewBag or TempData?

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!

Upvotes: 1

Views: 184

Answers (2)

Tushar Gupta
Tushar Gupta

Reputation: 15933

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.

Upvotes: 0

Zohaib Waqar
Zohaib Waqar

Reputation: 1229

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...

Upvotes: 1

Related Questions