Search code examples
asp.net-mvccontrollerviewbag

Can't access value of view bag in view set in controller


I am unable to access value of Viewbag.IsTeacher=i; in view. What i am doing wrong or there is some thing more to do to access value of view bag ? I want to add an 'if' condition depending on the value of Viewbag.IsTeacher=i;. Spend hours on this but could not get any proper solution.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user
        try
        {
            //UserProfile u = new UserProfile();
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
            WebSecurity.Login(model.UserName, model.Password);
            //var vRole = Request["selectRole"];
            //u =db.UserProfiles.Find(WebSecurity.CurrentUserId);
            var vRole = Request["selectRole"];
            int i = 0;
            if (vRole.Equals("teacher"))
            {
                i = 1;
                //ViewBag.rolee = "teacher";
                //u.IsTeacher = 1;
            }
            else
            {
                i = 0;
            }
            ViewBag.IsTeacher = i; 
            //ViewBag.rolee = "student";

            return RedirectToAction("Index", "Home");
        }
        catch (MembershipCreateUserException e)
        {
            ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
        }
    }

    // If we got this far, something failed, redisplay form

    return View(model);
}

View:

@if (Request.IsAuthenticated && ViewBag.IsTeacher == 1)
{
    <li>@Html.ActionLink("Quiz Management", "Index", "Quiz")</li>
    <li>@Html.ActionLink("Browse Quizzes", "Index", "TakeQuiz")</li>
    <li>@Html.ActionLink("Assignment Scheduling", "Index", "Assignment</li>
}

Solution

  • ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current user’s session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.

    In your Register action you would have:

    TempData["Role"] = Request["selectRole"];
    

    In your Index action you would have:

    ViewBag.IsTeacher = (TempData["Role"] != null && TempData["Role"] == "teacher");
    

    Then in your view you would have:

    ... ViewBag.IsTeacher == true ...