如何将部分视图渲染为字符串
我有以下代码:
public ActionResult SomeAction()
{
return new JsonpResult
{
Data = new { Widget = "some partial html for the widget" }
};
}
我想修改它,以便我可以
public ActionResult SomeAction()
{
// will render HTML that I can pass to the JSONP result to return.
var partial = RenderPartial(viewModel);
return new JsonpResult
{
Data = new { Widget = partial }
};
}
这样做吗?有人可以解释一下怎么做吗?
注意,我在发布解决方案之前编辑了问题。
I have the following code:
public ActionResult SomeAction()
{
return new JsonpResult
{
Data = new { Widget = "some partial html for the widget" }
};
}
I'd like to modify it so that I could have
public ActionResult SomeAction()
{
// will render HTML that I can pass to the JSONP result to return.
var partial = RenderPartial(viewModel);
return new JsonpResult
{
Data = new { Widget = partial }
};
}
is this possible? Could somebody explain how?
note, I edited the question before posting the solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
我为 ASP.NET MVC 4 应用程序选择了如下扩展方法。我认为它比我见过的一些建议更简单:
它允许我执行以下操作:
此外,此方法会保留任何 Model、ViewBag 和其他视图数据的观点。
I opted for an extension method like the following for an ASP.NET MVC 4 app. I think it's simpler than some of the suggestions I've seen:
It allows me to do the following:
Also, this approach persists any Model, ViewBag and other view data for the view.
这是一个有效答案的稍微修改版本:
用法:
This is a slightly modified version of an answer that works:
Usage:
DaveDev 的答案对我来说效果很好,但是当部分视图调用另一个部分视图时,我得到“值不能为空。参数名称:视图”
搜索周围我做了一个变体 以下 似乎效果很好。
用法:
DaveDev's answer worked well for me, however when the partial view calls another partial I get "Value cannot be null. Parameter name: view"
Searching around I have made a variant of the following that seems to work well.
Usage:
您可以创建将视图呈现为字符串的扩展。
然后在行动中使用它
You can create extension that render view into string.
And then use it in action
完美运行(仅需要查看名称)
* 对于参数,您可以使用模型
* 也可以从视图调用
此视图端或调用端
函数生成 HTML
部分视图页面
Works perfect (Only view name required)
* for parameters you can use a model
* can call this from a view also
View side or Calling Side
Function Generating HTML
Partial View page
您可以使用以下方法开箱即用:
You can do that out of the box with:
Dave,
同一主题的变体(mvc v1.0):
在控制器中的用法:
Dave,
a variation on the same theme (mvc v1.0):
usage within controller:
老帖子,但我认为你让这件事变得太困难了。
为什么不
return PartialView("", model);
将返回您想要的字符串。只需将 Get/Post 方法设置为
IActionResult
作为JsonResult
、PartialResult
以及其他继承自 ActionResult 的方法,您就可以发送回任何内容,包括JsonResult阿贾克斯
:
Old post, but I think you are making this too difficult.
Why not
return PartialView("<my partial>", model);
will return the string you desire.Just make the Get/Post method an
IActionResult
asJsonResult
,PartialResult
and other inherit from ActionResult you can send back anything including aJsonResult
Ajax:
使用 ASP.NET Core 6.0,现有的答案都不适合我,所以我推出了自己的答案。
示例用法如下:
None of the existing answers worked for me, using ASP.NET Core 6.0, so I rolled my own.
Example usage would be: