Alex Rivera | Logout

ASP.NET MVC - Returning a PartialView to Ajax along with another object

Asked 2012-05-14T19:24:52.443
53

I am writing a single page ajax app with ASP.NET MVC - making heavy use of jQuery. I do something similar to the following throughout the app:

JS:

$.ajax({
    type: "GET",
    url: "/Home/GetSomePartialView/",
    data: someArguments,
    success: function (viewHTML) { 
        $("#someDiv").html(viewHTML); 
    },
    error: function (errorData) { onError(errorData); }
});

Controller C#:

public ActionResult GetSomePartialView(SomeArgumentModel someArguments)
{
    
    return PartialView("_CaseManager");
}

This works great. The viewHTML (in the ajax success function) is returned as a string and I can shove it on the page no problem.

Now what I would like to do is to return not only the PartialView HTML string, but also some sort of status indicator. This is a permissions thing - for instance, if someone tries to get to a portion of they app they don't have permission to, I want to return a different PartialView than they asked for and also display a message in a popup window telling them why they got an View different from what they asked for.

So - to do this, I would like to do the following:

Controller C#:

public ActionResult GetSomePartialView(SomeArgumentModel someArguments)
{
    ReturnArgs r = new ReturnArgs();
    
    bool isAllowed = CheckPermissions(); 
    
    if (isAllowed) 
    {
        r.Status = 400; //good status ... proceed normally
        r.View = PartialView("_CaseManager");
    }
    else
    {
        r.Status = 300; //not good ... display permissions pop up
        r.View = PartialView("_DefaultView");
    }
    
    return Json(r);
}

public class ReturnArgs
{
    public ReturnArgs()
    {
    }

    public int Status { get; set; }
    public PartialViewResult View { get; set; }
}

JS:

$.ajax({
    type: "GE
Edit
Report

1 Answer

9

one way to skip having to return a json with multiple parameters and your html encoded as json is to send an HTML always but you send a hidden field that has the status set in it or something like that..

success: function(data)
{
  if(data.find("#ajax-status").val()==="success")
  {
    $("#someDiv").html(data);
  }
  else
  {
    showPopup("You do not have access to that.");
  }
}

I wouldnt recommend this appraoch I would have two partial views one for the normal view and the other for the error/unauthorized case..

answered 2012-05-14T19:33:41.863

Your Answer