ASP.Net MVC - 需要与部分视图一起发送其他数据

发布于 2024-09-02 16:03:29 字数 242 浏览 2 评论 0原文

我需要将一些其他数据(最好封装在 JSON 对象中)发送到客户端。但除此之外,我还需要发送部分视图。现在我只能想到两种方法:

  1. 发送 JSON 对象,然后再次调用将部分视图的内容加载到 div 中。
  2. 将部分视图的 HTML 作为 JSON 对象的属性发送,然后将其加载到 div 中。

我将如何去做第二个选择?是否有命令将部分视图呈现为字符串?还是第一种方法更好?

干杯, 达米安

I need to send some other data, ideally wrapped in a JSON object, down to the client. As well as that however I need to send a Partial view. Now I can only think of two ways:

  1. Send JSON object and then make another call to load contents of partial view into div.
  2. Send HTML for Partial View as a property of the JSON object and then load it into div.

How would I go about doing the second option? Is there a command to render partial views into a string? Or is the first approach better?

Cheers,
Damien

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

殊姿 2024-09-09 16:03:29

有没有渲染部分的命令
将视图转换为字符串

据我所知,没有直接的方法 但通过一些嘲笑是可能的。我在这里使用 Moq ,但任何模拟框架都可以。

var writer = new StringWriter();
var context = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();
context.Setup(ctx => ctx.Response).Returns(response.Object);
response.Setup(res => res.Output).Returns(writer);

var oldContext = ControllerContext.HttpContext;
ControllerContext.HttpContext = context.Object;

var partialView = PartialView("TagCloud", tags);
partialView.ExecuteResult(ControllerContext);
var resultHtml = writer.ToString();

ControllerContext.HttpContext = oldContext;

Is there a command to render partial
views into a string

No direct way as I know of. But it's possible with some mocking. I use Moq here, but any mocking framework would do.

var writer = new StringWriter();
var context = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();
context.Setup(ctx => ctx.Response).Returns(response.Object);
response.Setup(res => res.Output).Returns(writer);

var oldContext = ControllerContext.HttpContext;
ControllerContext.HttpContext = context.Object;

var partialView = PartialView("TagCloud", tags);
partialView.ExecuteResult(ControllerContext);
var resultHtml = writer.ToString();

ControllerContext.HttpContext = oldContext;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文