0

I am beginner in ASP.NET and trying to get data in ViewBagby using temp data in controller. I got it in user.Username and user.Email but not getting in ViewBag.Name and ViewBag.Email respectively. My code is given below please guide me how can i get it in ViewBag?

QuestionsContoller.cs

public class temp {
    public string username { get; set; }
    public string email { get; set; }
}

public ActionResult Question() {
    return View();
}

[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult Question(User user) {
    temp temp_user = new temp();
    temp_user.email = user.Email;
    temp_user.username = user.Username;
    return RedirectToAction("Answers" , temp_user);
}

public ActionResult Answers(temp temp_user) {
    User user = new Models.User();
    user.Username = temp_user.username;
    user.Email = temp_user.email;
    ViewBag.Name = user.Username;
    ViewBag.Email = user.Email;
    return View(user);
}
8
  • What do you mean by "how can i get it in ViewBag?" ? Do you want to get your ViewBag data into your view ? Commented May 8, 2017 at 17:51
  • yes, after it I will get it in my View. Commented May 8, 2017 at 17:57
  • So you need to know to get the data into the View, right? Commented May 8, 2017 at 17:58
  • yes... I can call it in my View. But before it I want to get it in my ViewBag. Commented May 8, 2017 at 18:00
  • 1
    I realy don't understand what you need to do. Commented May 8, 2017 at 18:01

1 Answer 1

1

You cannot redirect with a payload. A redirect is an empty-bodied response with typically a 302 status code and a Location header indicating the URL that should be requested next. The client, upon receiving this type of response, will generally then go ahead and make a new request for that URL. Importantly, the client will not know or care to pass any additional data along with this request, so you cannot enforce that something like your temp object is included.

If you need to persist that data between requests, you can add it to TempData:

TempData["temp_user"] = temp_user;

And then fetch it in the action you redirect to via:

 var temp_user = TempData["temp_user"] as temp;

Alternatively (and preferably), you'd simply redirect with the user id in tow, and then simply look up the user again. The use of sessions (which TempData is) should be avoided as much as possible.

return RedirectToAction("Answers", new { userId = user.Id });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.