0

I have a ViewBag in my page. When the page is loading, it is showing the ViewBag value.

I also have a DropDownList. I want to change the ViewBag value on selection change event and post the value to the Controller via ajax. Controller is also returning the proper value.

In my code the ViewBag is being updated, but it is not being displayed on the html(on browser).

I don't have any kind of clue why its not working!

My View

<div id="UserSelection">--Select User--
    @Html.DropDownListFor(m => m.Item1, new SelectList(Users, "ID", "Names"), new { ID = "UserSelection", @Style = "width:50%;border:none" })
</div>

@Html.Raw(ViewBag.UserID)

My Controller

public ActionResult Permission()
{
    ViewBag.UserID = Session["UserID"].ToString();
    ViewBag.Permissions = Session["PermissionCollection"] as List<int>;

    return View();
}

[HttpPost]
public ActionResult Users(string UserID)
{
    List<int> data = new List<int>();
    int id = Convert.ToInt16(UserID);

    Permission perm = new Permission();
    data = perm.SlectedPermissions(id);

    ViewBag.UserID = UserID.ToString();
    ViewBag.Permissions = data as List<int>;

    return View("Permission");
}

My jQuery

$("#UserSelection").change(function () {
    var ID = $('#UserSelection option:selected').val();
    console.log(ID);
    $("#empID").val(ID);
    $.ajax({
        traditional: true,
        async: false,
        url: '@Url.Content("~/Permission/Users")',
        type: "POST",
        data: { UserID: ID },
        success: function (data) {
        }
    });               
});
Devraj Gadhavi
  • 3,541
  • 3
  • 38
  • 67
  • How do you expect the data to be updated when you are making an ajax call and not updating the front end with your result? I bet if you did a normal post it would work fine – Pete Jan 09 '14 at 10:36
  • Change `url: '@Url.Content("~/Permission/Users")',` to `url: '@Url.Action("Users", "Permission")',`. Content is used for static files (i.e. images) while Action is used for urls in your application. – Marthijn Jan 09 '14 at 14:21

1 Answers1

0

Your view Permissions.cshtml does not using ViewBag.Permissions.

You can access ViewBag data only in the returning view, in this case it is Permissions.cshtml.

This @Html.Raw(ViewBag.UserID) code is defined in a main view and not part of Permissions view. Hence it is not working for you

Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120