0

In a asp.net mvc project i have this on top of my index.cshtml file

$.ajax({
    url: '@Url.Action("getLoggedUser", "Home")',
    dataType: "html",
    "async": true,
    type: "GET",
    success: function (data) {

    },
});

And the method it uses is this one, that is on HomeController

public async Task getLoggedUser()
{
    try
    {
        BenchesService benchService = new BenchesService();
        UserTest LoggedUser = new UserTest();
        string name = Request.RequestContext.HttpContext.User.Identity.Name;
        name = name.Substring(name.LastIndexOf('\\') + 1);
        LoggedUser = await benchService.getCurrentUser(name);
        role = LoggedUser.role;
        ViewBag.LoggedUser = LoggedUser.role;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

This does a GET to the server with getCurrentUser(name); and that returns a json with user info, that i use to fill a UserTest object (i checked with break and the LoggedUser is filled correctly).

I want to save the user Role, to use in the html / javascript part

Then again on my index.cshtml i have this other script

$(document).ready(function () {
    setTimeout(function () {
        console.log("TIMER!");
        userRole = '@ViewBag.LoggedUser';
        alert(userRole);
    }, 5000);

My problem is that the alert shows a empty message, like the ViewBag.LoggedUser has nothing. am i using ViewBag wrong?

5
  • 1
    returns a json with user info No it doesn't... You are not returning anything. Commented Sep 9, 2015 at 8:33
  • 1
    ViewBag can only be read at the server side. Return a json with logged user and access it in the success callback and you shoukd be fine. Commented Sep 9, 2015 at 8:33
  • i explained wrong, ill fix my post Commented Sep 9, 2015 at 8:37
  • 1
    @ViewBag.LoggedUser is razor code - its parsed on the server before its sent to the client so if @ViewBag.LoggedUser is null in you GET method that generated the view, it will alert nothing. Your ajax method calls a method which return nothing. Commented Sep 9, 2015 at 8:41
  • 1
    This is completely wrong. Use Strongly typed models and then actually return something from your GET on the controller. Commented Sep 9, 2015 at 8:42

1 Answer 1

3

Are you reloading your page? If not, your ViewBag has the same content like in the moment when page was rendering. Razor render text from ViewBag only on creation of html page, and if you are not reloading page, it will be always empty. You have to return your data in some object (ex. json) to ajax request and then you can use it.

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.