I would like to render a PartialView to an HTML string so I can return it to a SignalR ajax request.
Something like:
SignalR Hub (mySignalHub.cs)
public class mySignalRHub: Hub
{
public string getTableHTML()
{
return PartialView("_MyTablePartialView", GetDataItems()) // *How is it possible to do this*
}
}
Razor PartialView (_MyTablePartialView.cshtml)
@model IEnumerable<DataItem>
<table>
<tbody>
@foreach (var dataItem in Model)
{
<tr>
<td>@dataItem.Value1</td>
<td>@dataItem.Value2</td>
</tr>
}
</tbody>
</table>
HTML (MySignalRWebPage.html)
<Script>
...
//Get HTML from SignalR function call
var tableHtml = $.connection.mySignalRHub.getTableHTML();
//Inject into div
$('#tableContainer).html(tableHtml);
</Script>
<div id="tableContainer"></div>
My problem is that I can't seem to render a PartialView outside of a Controller. Is it even possible to render a PartialView outside of a Controller? It would be very nice to still be able to leverage the awesome HTML generating abilities that come with Razor.
Am I going about this all wrong? Is there another way?
Here, this is what I use in Controllers for ajax, I modified it a bit so it can be called from method instead of controller, method
returnView
renders your view and returns HTML string so you can insert it with JS/jQuery into your page when you recive it on client side:I didn't test it on a Hub but it should work.
Based on the answers supplied to asimilar question below, I would suggest using
Html.Partial(partialViewName)
It returns an MvcHtmlString, which you should able to use as the content of your SignalR reponse. I have not tested this, however.
Stack Overflow Question: Is it possible to render a view outside a controller?
Have you thought about using a razor template engine like http://razorengine.codeplex.com/ ? You can't use it to parse partial views but you can use it to parse razor templates, which are almost similar to partial views.
How about using the
RazorEngineHost
andRazorTemplateEngine
. I found this nice article that might be what you're looking for. It's about hosting Razor outside of ASP.NET (MVC).Further to the answer provided by @user1010609 above, I struggled through this as well and have ended up with a function that returns the rendered PartialView given a controller name, path to the view and model.
Takes account of the fact you don't have a controller and hence none of the usual state as coming from a SignalR event.
You would call it with something similar to:
Probably the best choice is to use RazorEngine, as Wim is suggesting.