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

后端 未结 2 575
不思量自难忘°
不思量自难忘° 2020-11-30 18:47

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:

$         


        
2条回答
  •  半阙折子戏
    2020-11-30 19:04

    So - using the following posts I got this working:

    Partial Views vs. Json (or both)

    Render a view as a string

    They both lay it out nicely, then I changed my code to the following:

    C#:

    public ActionResult GetSomePartialView(SomeArgumentModel someArguments)
    {
        ReturnArgs r = new ReturnArgs();
    
        bool isAllowed = CheckPermissions(); 
    
        if (isAllowed) 
        {
            r.Status = 400; //good status ... proceed normally
            r.ViewString = this.RenderViewToString("_CaseManager");
        }
        else
        {
            r.Status = 300; //not good ... display permissions pop up
            r.ViewString = this.RenderViewToString("_DefaultView");
        }
    
        return Json(r);
    }
    
    public class ReturnArgs
    {
        public ReturnArgs()
        {
        }
    
        public int Status { get; set; }
        public string ViewString { get; set; }
    }
    

    JS:

    $.ajax({
        type: "GET",
        url: "/Home/GetSomePartialView/",
        data: someArguments,
        success: function (jsReturnArgs) { 
    
            if (jsReturnArgs.Status === 300) { //300 is an arbitrary value I just made up right now
                showPopup("You do not have access to that.");
            }
    
            $("#someDiv").html(jsReturnArgs.ViewString); //the HTML I returned from the controller
        },
        error: function (errorData) { onError(errorData); }
    });
    

提交回复
热议问题