简体   繁体   English

Asp.net MVC:在Json对象内发送回HTML

[英]Asp.net MVC: Send back HTML inside Json object

I want to return back html inside my json object however this does not seem to work, my code: 我想在json对象中返回html,但是这似乎不起作用,我的代码是:

return new JsonResult()
{
 Data = new { Error = false, NewComment = PartialView("Review/InlineCommentUC", dto) }
};

I want NewComment to have some html inside it... 我希望NewComment里面有一些html ...

What I recieve (using firebug) for the NewComment object in json format is: 我收到的(使用Firebug)JSON格式的NewComment对象是:

TempData = []
View = null,
ViewData = []
ViewEngineCollection = some data..
ViewName = name of view

I am using Jquery to render the output onto the html, the reason for sending back a json object is, so I can handle my errors very easily. 我正在使用Jquery将输出呈现到html上,发送回json对象的原因是,因此我可以非常轻松地处理错误。

Ideally a custom Action Result is what I am looking for... 理想情况下,我要寻找自定义操作结果...

Is http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/ what you're looking for? 您正在寻找http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/吗?

Copied using the WayBackMachine. 使用WayBackMachine复制。

I have run into a situation where I would like to render a partial view to a string and then return it as part of a JSON response like so: 我遇到了一种情况,我想呈现字符串的部分视图,然后将其作为JSON响应的一部分返回,如下所示:

return Json(new {
    statusCode = 1,
    statusMessage = "The person has been added!",
    personHtml = PartialView("Person", person)
});

The ability to do something like this would open up a ton of amazing possibilities, so I really scoured the internet looking for a solution. 做这样的事情的能力会带来很多惊人的可能性,所以我真的在互联网上搜寻了一个解决方案。 Unfortunately, no one seems to have come up with a clean solution for it, so I dug into the MVC code and came up one…and because I'm such a nice guy, you get to copy it for free. 不幸的是,似乎没有人提出一个干净的解决方案,因此我研究了MVC代码并提出了一个……因为我是如此的好,您可以免费复制它。 ;) ;)

public abstract class MyBaseController : Controller {

    protected string RenderPartialViewToString()
    {
        return RenderPartialViewToString(null, null);
    }

    protected string RenderPartialViewToString(string viewName)
    {
        return RenderPartialViewToString(viewName, null);
    }

    protected string RenderPartialViewToString(object model)
    {
        return RenderPartialViewToString(null, model);
    }

    protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = ControllerContext.RouteData.GetRequiredString("action");

        ViewData.Model = model;

        using (StringWriter sw = new StringWriter()) {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

Now you can simply do this: 现在,您可以简单地执行以下操作:

public class MyController : MyBaseController {

    public ActionResult CreatePerson(Person p) {
        if (ModelState.IsValid) {
            try {
                PersonRepository.Create(p);
                return Json(new {
                    statusCode = 1,
                    statusMessage = "The person has been added!",
                    personHtml = RenderPartialViewToString("Person", p)
                });
            }
            catch (Exception ex) {
                return Json(new {
                    statusCode = 0,
                    statusMessage = "Error: " + ex.Message
                });
            }
        }
        else
            return Json(new {
                statusCode = 0,
                statusMessage = "Invalid data!"
            });
    }
}

Also note that you can modify these functions to render a View (rather than a PartialView) with this small change: 还请注意,您可以修改这些函数以通过以下较小的更改来呈现视图(而不是PartialView):

ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName);

Enjoy! 请享用!

PartialView returns a PartialViewResult docs and that is what gets encoded to JSON. PartialView返回一个PartialViewResult 文档 ,这就是被编码为JSON的内容。

Look at http://forums.asp.net/post/3761391.aspx on how to render the PartialView to a string 查看http://forums.asp.net/post/3761391.aspx ,了解如何将PartialView呈现为字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM