问题
I have the requirement to use Html.RenderAction like you would in ASP.NET MVC.
For instance I have a Home Page with News and Products on.
I would like to do for instance
@Html.RenderAction("/api/products/featured")
Which would start a new service call and output the template to the html stream.
Is this possible using ServiceStack Razor and if so how do I accomplish it?
回答1:
The PartialExamples.cshtml test page shows different examples of rendering a razor view inside a page, e.g:
Using the new RenderToAction()
method which lets you execute a Service and it's rendered partial view with a route and QueryString, e.g:
@Html.RenderAction("/products/1")
This also takes an optional view name if you want a different view than the default:
@Html.RenderAction("/products/1", "CustomProductView")
There's also the normal Html.Partial()
to specify which view and model you want to render in the page, e.g:
@Html.Partial("GetProduct",
base.ExecuteService<ProductService>(s => s.Any(new GetProduct { Id = 1 })))
ExecuteService
is simply a wrapper around the equivalent ResolveService
in a using statement, i.e:
@{
Response response = null;
using (var service = base.ResolveService<ProductService>())
{
response = service.Any(new GetProduct { Id = 1 });
}
}
@Html.Partial("GetProduct", response)
The new RenderToAction()
method in Razor Views was added in v4.0.34+ which is now available on MyGet.
回答2:
*I may be duplicating my answer or I lost it somehow
Looking at the ServiceStack.Razor.ViewPage class there is an Html property of type ServiceStack.Html.HtmlHelper. I don't see 'RenderAction' as a method (or extension method) on this class so it doesn't appear to be available. There is a 'Partial' method that takes the ViewName and an overload that takes a ViewName and an object. Based on your above comment this doesn't appear to be a useful solution.
If I'm correct about the above, I think you'd need your 'Featured View Template' to pull in the data. Could add soemthing like
{ FeaturedResponse products = new JsonServiceClient("http://localhost").Get<FeaturedResponse>("/api/products/featured"); }
to your template. This would allow you to use the products variable like a Model.
Or, use JavaScript to pull the data into the template. You would have have to use JavaScript to get your data into the HTML elements, though.
You could then render the template using @Html.Partial('Featured')
Hope this helps.
来源:https://stackoverflow.com/questions/15028447/servicestack-razor-html-renderaction-equivalent