For very simple ViewComponents I'd like to bypass a view and just return an encoded HTML string.
Example:
<ul>
<li>One</li>
<li>Two</li>
<ul>
My self-made implementation is like this:
public class RawHtmlResult : IViewComponentResult
{
public RawHtmlResult(string EncodedHtml)
{
_encodedHtml = EncodedHtml;
}
public string _encodedHtml { get; set; }
public void Execute(ViewComponentContext context)
{
context.Writer.Write(_encodedHtml);
}
public Task ExecuteAsync(ViewComponentContext context)
{
return context.Writer.WriteAsync(_encodedHtml);
}
}
Usage:
public async Task<IViewComponentResult> InvokeAsync(long id)
{
var someArray = await _someService(id);
var ulHelper = new TagBuilder("ul");
var liHelper = new TagBuilder("li");
foreach (var setName in someArray)
{
liHelper = new TagBuilder("li");
liHelper.InnerHtml.Append(setName);
ulHelper.InnerHtml.Append(liHelper);
}
var writer = new System.IO.StringWriter();
ulHelper.WriteTo(writer, new HtmlEncoder());
return new RawHtmlResult(writer.ToString());
}
So far I have not found a suitable IViewComponentResult. Do I miss apoint?
The Invoke()
method on the view component does not need to return IViewComponentResult
, it can return HtmlString
so you don't need a custom implementation of IViewComponentResult
.
For example:
public HtmlString Invoke()
{
return new HtmlString(@"<b>Hello World</b>");
}
return Content("<ul><li>One</li><li>Two</li><ul>");
The method is Controller.Content. You can also use it to return content types other than HTML.
As mentioned it's not the preferred way to return HTML - typically the controller should return a model and the view should provide HTML. It might be preferable to use a partial view. But scenarios come up where we have to do things like this. (I just encountered one myself.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With