How to pass in HTML to a Razor Partial View?
Asked Answered
N

2

6

I want to pass in HTML to my partial view, like so:

@Html.Partial("_MyForm", "<button id='foo'>Process Data</button>")

This currently works, but passing in strings is inelegant. Previously, IHTMLString allowed you to do this instead (see link):

public class HTMLViewModel
{
    public Func<object, IHtmlString> Content { get; set; }
}

@Html.Partial("_MyForm", new HTMLViewModel()
{
    Content =  
    @<button>
       <h1>Hello World</h1>
    </button>
})

IHTMLString no longer exists in .NET Core, can the approach still be replicated with some other feature?

Nibble answered 21/6, 2019 at 14:6 Comment(0)
C
4

You can use IHtmlContent to maintain your current approach:

public Func<object, IHtmlContent> Content { get; set; }

And then in the partial:

@model HTMLViewModel
@Model.Content(null)

Depending on which version of .NET Core you're using you could also take advantage of some of the inline function markup changes discussed here: https://github.com/aspnet/AspNetCore-Tooling/pull/334

Cavalierly answered 21/6, 2019 at 19:17 Comment(1)
is this still the way to go?Magnific
B
0

For aspnet core razor take a look at "Templated Razor delegates" documentation

Your syntax should work:

public class HTMLViewModel
{
    public Func<dynamic, object> Content { get; set; }
}

@Html.Partial("_MyForm", new HTMLViewModel()
{
    Content =  
    @<button>
       <h1>Hello World</h1>
    </button>
})

More generally, you can create strongly typed templates as well:

Func<T, object> template = @<div>@item.Foo</div>;

(where T is your type).

You can then pass that function around (in to your partial view) and invoke as such:

@template(new T { Foo = "Bar" })

Notice that the parameter passed in is accessed via @item. (My VS adds a red squiggle for this but it can be ignored!)

Bassoon answered 29/11, 2023 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.