从控制器内部获取局部视图的 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/286132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting a Partial View's HTML from inside of the controller
提问by Andrew Harry
I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div. All is well and it looks cool.
My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.
我为我的 mvc 网站开发了一个简单的机制,通过 jquery 拉入 html,然后填充指定的 div。一切都很好,看起来很酷。
我的问题是我现在正在我的控制器内部创建 html 标记(这在 VB.net 中很容易做到) 我宁愿不混淆关注点的分离。
Is it possible to use a custom 'MVC View User Control' to suit this need? Can I create an instance of a control, pass in the model data and render to html? It would then be a simple matter of rendering and passing back to the calling browser.
是否可以使用自定义的“MVC 视图用户控件”来满足此需求?我可以创建一个控件实例,传入模型数据并渲染到 html 吗?那么渲染和传递回调用浏览器将是一个简单的问题。
采纳答案by Todd Smith
You have several options.
您有多种选择。
Create a MVC View User Control and action handler in your controller for the view. To render the view use
在控制器中为视图创建一个 MVC 视图用户控件和操作处理程序。渲染视图使用
<% Html.RenderPartial("MyControl") %>
In this case your action handler will need to pass the model data to the view
在这种情况下,您的操作处理程序需要将模型数据传递给视图
public ActionResult MyControl ()
{
// get modelData
render View (modelData);
}
Your other option is to pass the model data from the parent page. In this case you do not need an action handler and the model type is the same as the parent:
您的另一个选择是从父页面传递模型数据。在这种情况下,您不需要动作处理程序并且模型类型与父级相同:
<% Html.RenderPartial("MyControl", ViewData.Model) %>
If your user control has it's own data type you can also construct it within the page
如果你的用户控件有它自己的数据类型,你也可以在页面中构造它
In MyControl.ascx.cs:
在 MyControl.ascx.cs 中:
public class MyControlViewData
{
public string Name { get; set; }
public string Email { get; set; }
}
public partial class MyControl : System.Web.Mvc.ViewUserControl <MyControlViewData>
{
}
And in your page you can initialize your control's data model:
在您的页面中,您可以初始化控件的数据模型:
<% Html.RenderPartial("MyControl", new MyControlViewData ()
{
Name= ViewData.Model.FirstName,
Email = ViewData.Model.Email,
});
%>
回答by pupeno
This is a solution that is working with ASP.Net MVC 1.0 (many that claim to work with beta 3 don't work with 1.0), doesn't suffer of the 'Server cannot set content type after HTTP headers have been sent' problem and can be called from within a controller (not only a view):
这是一个适用于 ASP.Net MVC 1.0 的解决方案(许多声称适用于 beta 3 的解决方案不适用于 1.0),不会遇到“发送 HTTP 标头后服务器无法设置内容类型”问题并且可以从控制器(不仅仅是视图)中调用:
/// <summary>
/// Render a view into a string. It's a hack, it may fail badly.
/// </summary>
/// <param name="name">Name of the view, that is, its path.</param>
/// <param name="data">Data to pass to the view, a model or something like that.</param>
/// <returns>A string with the (HTML of) view.</returns>
public static string RenderPartialToString(string controlName, object viewData) {
ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };
viewPage.Url = GetBogusUrlHelper();
viewPage.ViewData = new ViewDataDictionary(viewData);
viewPage.Controls.Add(viewPage.LoadControl(controlName));
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb)) {
using (HtmlTextWriter tw = new HtmlTextWriter(sw)) {
viewPage.RenderControl(tw);
}
}
return sb.ToString();
}
public static UrlHelper GetBogusUrlHelper() {
var httpContext = HttpContext.Current;
if (httpContext == null) {
var request = new HttpRequest("/", Config.Url.ToString(), "");
var response = new HttpResponse(new StringWriter());
httpContext = new HttpContext(request, response);
}
var httpContextBase = new HttpContextWrapper(httpContext);
var routeData = new RouteData();
var requestContext = new RequestContext(httpContextBase, routeData);
return new UrlHelper(requestContext);
}
It's a static method you can drop somewhere you find it convenient. You can call it this way:
这是一个静态方法,您可以将其放在您觉得方便的地方。你可以这样称呼它:
string view = RenderPartialToString("~/Views/Controller/AView.ascx", someModelObject);
回答by Kevin Zink
I put together a rough framework which allows you to render views to a string from a controller method in MVC Beta. This should help solve this limitation for now.
我整理了一个粗略的框架,它允许您将视图从 MVC Beta 中的控制器方法呈现为字符串。这应该有助于暂时解决此限制。
Additionally, I also put together a Rails-like RJS javascript generating framework for MVC Beta.
此外,我还为 MVC Beta 构建了一个类似于 Rails 的 RJS javascript 生成框架。
Check it out at http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvcand let me know what you think.
在http://www.brightmix.com/blog/how-to-renderpartial-to-string-in-asp-net-mvc 上查看并告诉我您的想法。
回答by Christian Dalager
You would create your action like this:
你会像这样创建你的动作:
public PartialViewResult LoginForm()
{
var model = // get model data from somewhere
return PartialView(model);
}
And the action would return the rendered partial view to your jquery response.
并且该操作会将呈现的部分视图返回到您的 jquery 响应。
Your jquery could look something like this:
您的 jquery 可能如下所示:
$('#targetdiv').load('/MyController/LoginForm',function(){alert('complete!');});
回答by Hrvoje Hudo
You should use jquery to populate your divs (and create new html elements if needed), and Json serialization for ActionResult.
您应该使用 jquery 来填充您的 div(并在需要时创建新的 html 元素),并使用 Json 序列化 ActionResult。
Other way is to use jquery to call some controller/action, but instead json use regular View (aspx or ascx, webforms view engine) for rendering content, and with jquery just inject that html to some div. This is half way to UpdatePanels from asp.net ajax...
另一种方法是使用 jquery 来调用一些控制器/动作,但 json 使用常规视图(aspx 或 ascx,webforms 视图引擎)来呈现内容,而 jquery 只是将该 html 注入到某个 div 中。这是从 asp.net ajax 到 UpdatePanels 的一半...
I would probably go with first method, with json, where you have little more job to do, but it's much more "optimized", because you don't transfer whole html over the wire, there are just serialized objects. It's the way that "big ones" (gmail, g docs, hotmail,..) do it - lot of JS code that manipulates with UI.
我可能会使用第一种方法,使用 json,在那里您几乎没有更多工作要做,但它更加“优化”,因为您不会通过网络传输整个 html,只有序列化的对象。这是“大公司”(gmail、g docs、hotmail 等)的做法 - 大量使用 UI 操作的 JS 代码。
If you don't need ajax, then you basically have two ways of calling partial views:
如果你不需要ajax,那么你基本上有两种调用局部视图的方法:
- html.renderpartial("name of ascx")
- html.RenderAction(x=>x.ActionName) from Microsoft.web.mvc (mvc futures)
- html.renderpartial("ascx 名称")
- html.RenderAction(x=>x.ActionName) 来自 Microsoft.web.mvc(mvc 期货)
回答by Andrew Harry
After much digging in google i have found the answer. You can not get easy access to the html outputted by the view.
经过在谷歌的大量挖掘后,我找到了答案。您无法轻松访问视图输出的 html。
回答by Rob King
I've done something similar for an app I'm working on. I have partial views returning rendered content can be called using their REST path or using:
我为我正在开发的应用程序做了类似的事情。我有返回渲染内容的部分视图可以使用它们的 REST 路径或使用:
<% Html.RenderAction("Action", "Controller"); %>
Then in my actual display HTML I have a DIV which is filled from jQuery:
然后在我的实际显示 HTML 中,我有一个由 jQuery 填充的 DIV:
<div class="onload">/controller/action</div>
The jQuery looks like this:
jQuery 看起来像这样:
<script type="text/javascript">
$.ajaxSetup({ cache: false });
$(document).ready(function () {
$('div.onload').each(function () {
var source = $(this).html();
if (source != "") {
$(this).load(source);
}
});
});
</script>
This scans for all DIV that match the "onload" class and reads the REST path from their content. It then does a jQuery.load on that REST path and populates the DIV with the result.
这将扫描与“onload”类匹配的所有 DIV,并从它们的内容中读取 REST 路径。然后它在该 REST 路径上执行 jQuery.load 并用结果填充 DIV。
Sorry gotta go catch my ride home. Let me know if you want me to elaborate more.
对不起,要赶我的车回家。如果您想让我详细说明,请告诉我。
回答by Paco Lf
it is very simple you just have to create a strongly typed partial view(or user control) then in your cotroller something like this:
这很简单,您只需要创建一个强类型的局部视图(或用户控件),然后在您的控制器中创建如下内容:
public PartialViewResult yourpartialviewresult()
{
var yourModel
return PartialView("yourPartialView", yourModel);
}
then you can use JQuery to perform the request whener you want:
然后您可以使用 JQuery 随时执行请求:
$.ajax({
type: 'GET',
url: '/home/yourpartialviewresult',
dataType: 'html', //be sure to use html dataType
contentType: 'application/json; charset=utf-8',
success: function(data){
$(container).html(data);
},
complete: function(){ }
});
回答by Himanshu Patel
I found this one line code to work perfectly. orderModel being my model object. In my case I had a helper method in which I had to merge a partial view's html.
我发现这一行代码可以完美地工作。orderModel 是我的模型对象。就我而言,我有一个辅助方法,我必须在其中合并部分视图的 html。
System.Web.Mvc.Html.PartialExtensions.Partial(html, "~/Views/Orders/OrdersPartialView.cshtml", orderModel).ToString();
回答by Orion Edwards
In rails this is called rendering a partial view, and you do it with render :partial => 'yourfilename'
. I believe ASP.NET MVC has a similar RenderPartial
method, but I can't find the official docs for MVC to confirm or deny such a thing.
在 rails 中,这称为渲染局部视图,您可以使用render :partial => 'yourfilename'
. 我相信 ASP.NET MVC 有类似的RenderPartial
方法,但我找不到 MVC 的官方文档来确认或否认这样的事情。