Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason why my ViewBag is not working?

Tags:

asp.net-mvc

I have following ActionResult in a controller and you can see that I set a message in the ViewBag if it's successful. Then on the View it should output that message if it's not empty. However, I can't get the message to display and I'm not seeing what the problem is.

[HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
                {
                    Name = collection["RoleName"]
                });
                context.SaveChanges();

                ViewBag.ResultMessage = "Role created successfully.";
                return RedirectToAction("Index");
            }
            catch (Exception)
            {
                return View();
            }            
        }

This is my Index.cshtml

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>
@{
    ViewBag.Title = "Index";
}

<h2>Roles Listing </h2>

@ViewBag.ResultMessage

@Html.ActionLink("Create New Role", "Create") | @Html.ActionLink("Manage User Role", "ManageUserRoles")

<div>
    <table class="table table-bordered table-condensed table-striped table-hover ">
        <thead>
            <tr>
                <th>Role</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var role in Model)
            {
                <tr>
                    <td><strong>@role.Name</strong></td>
                    <td>
                        <span onclick="return confirm('Are you sure you want to delete @role.Name?')"><a href="/Roles/[email protected]" class="delLink" style="color:red;">Delete</a></span> |
                        @Html.ActionLink("Edit", "Edit", new { roleName = @role.Name })
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>
like image 833
Caverman Avatar asked Dec 24 '15 04:12

Caverman


2 Answers

ViewBag helps to maintain data when you move from controller to view. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Since you are using RedirectToAction, the ViewBag becomes null when it reaches the view.

you can use TempData for this:

TempData["ResultMessage"] = "Role created successfully.";

It uses Session as storage, but it will not be around after the second response. TempData helps to maintain data when you move from one controller to other controller or from one action to other action. In other words, when you redirect, Tempdata helps to maintain data between those redirects. It internally uses session variables. TempData use during the current and subsequent request only means it is used when you are sure that next request will be redirecting to next view.

For more understanding on this refer this link

like image 192
Senjuti Mahapatra Avatar answered Sep 18 '22 18:09

Senjuti Mahapatra


The ViewBag property enables you to dynamically share values from the controller to the view. (MSDN)

It’s life lies only during the current request, and if redirection occurs then it’s value becomes null. And since you using RedirectToAction, which redirects to some different controller, value of ViewBag is lost.

Consider using TempData instead.

TempData["ResultMessage"] = "Role created successfully.";

(See this for usage)

like image 37
Yogi Avatar answered Sep 18 '22 18:09

Yogi