Returning a PartialView with both HTML and JavaScript

后端 未结 4 464
终归单人心
终归单人心 2021-01-06 15:43

I am making an AJAX call (with jQuery) to retrieve a PartialView. Along with the HTML I\'d like to send back a JSON representation of the object the View is dis

4条回答
  •  天涯浪人
    2021-01-06 16:20

    Probably not the most elegant answer you'll get, but just to throw this out there:

    You could return purely json from your action method,

    something that would look like this:

    {
        Html: "
    etc...", Json: { // your object here } }

    in your controller you'll need something like this to render your view:

    var existingContext = HttpContext.Current;
    var writer = new StringWriter();
    var response = new HttpResponse(writer);
    var httpContext = new HttpContext(existingContext.Request, response);
    
    var viewResult = myAction(bla);
    
    HttpContext.Current = httpContext;
    
    viewResult.ExecuteResult(this.ControllerContext)
    
    HttpContext.Current = existingContext;
    var viewAsHtml = writer.ToString();
    

提交回复
热议问题