views:

40

answers:

1

Hey Everyone-

I have some code in a controller (HomeController.cs) that gets called from a $.get method in my view.

View Code

        $(document).ready(function() {
        $.get("/Home/Toolbar", function(result) {
            $("body").prepend(result);
        });
     });

HomeController.cs

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Toolbar()
    {
        if (Request.IsAuthenticated && Roles.IsUserInRole("Agents"))
            return PartialView("toolbar");

        return new EmptyResult();
    }

My issue here is after the EmptyViewResult is returned to the JS, the code doesn't "post back" to the controller anymore. If I remove the "if" conditional and consisently return the PartialView, everything works correctly.

I would like to only include the "toolbar" partial view in the DOM, when the user is in the "Agents" role.

+2  A: 

Since it doesn't look like you're doing much custom logic in your actionresult, why not just conditionally include the PartialView in your site.master (or wherever appropriate)? Since it isn't really dynamic (at least based on what I see in the controller) seems wasteful to open up another HTTP connection and grab it over AJAX.

Parrots
What is your describing is exactly what I was doing before, however the reason why I wanted to load the "toolbar" via ajax is because I would get the ability to use effects in jquery on it. For example, if I conditionally include it in the Master page, then it would get loaded into the DOM without AJAX, and I wouldnt be able to slide the toolbar div down using the "slide" effect. Maybe there is another way? This is just what ive experienced. What is the best way to do this type of thing? Is my method "best practice"?
j0nscalet
A much better way is to initially hide the parts you want to use jQuery animations on - say, using the CSS `display: none;`. Ajax loading immediately after a page load is not the right way to achieve what you want.
Matt Ball