Any reason my ViewBag is not working?

I have ActionResultin controller, and you can see that I set the message to ViewBagif it was successful. Then Viewhe should display this message if it is not empty. However, I cannot display the message, and I do not see 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/Delete?RoleName=@role.Name" class="delLink" style="color:red;">Delete</a></span> |
                        @Html.ActionLink("Edit", "Edit", new { roleName = @role.Name })
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>
+4
source share
3 answers

ViewBagHelps keep data moving from controllerto view. A short lifetime means that the value becomes zero when a redirect occurs. This is because their goal is to provide a way of communication between controllersand views. Its communication mechanism in the server call.

RedirectToAction, ViewBag null, view.

TempData :

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

Session , . TempData controller controller . , TempData . . TempData , , , .

+6

ViewBag . (MSDN)

, , . RedirectToAction, - , ViewBag.

TempData.

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

(. )

+2

/ . tempdata, ,

0

Source: https://habr.com/ru/post/1621570/


All Articles