How can I pass HTML content to a Partial View in MVC-Razor like a “for” block

半腔热情 提交于 2019-12-03 10:50:37

I was having the same dilemma. Try creating a viewmodel type with a Func property and then pass the html as delegate.

public class ContainerViewModel
{
    public String Caption { get; set; }
    public String Name { get; set; }
    public Int32 Width { get; set; }
    public Func<object, IHtmlString> Content { get; set; }
}

@Html.Partial("Container", new ContainerViewModel()
{
    Name = "test",
    Caption = "Test container",
    Content =  
    @<text>
       <h1>Hello World</h1>
    </text>,
    Width = 600
})

You can call it like this in your partial.

@Model.Content(null)

If you want to be fancy you can add this extension method.

public static class PartialExtensions
{
    public static IHtmlString Display<T>
        (this T model, Expression<Func<T, Func<Object, IHtmlString>>> content) 
    {
        var compiled = content.Compile();
        return compiled.Invoke(model).Invoke(null);
    }
}

Then, any time you use this pattern, you can call it like this in your partial (not fully tested).

@model ContainerViewModel
@Model.Display(m => m.Content)  // Use delegate property

Hope this works for you.

It works because the @... syntax creates a little HtmlHelper for you that consumes a Model (which you're declaring here as type object, and passing null for), and returns an IHtmlString.

BEWARE form values don't seem to post to the server if @Html.BeginForm is used in the content.

Therefore, wrap your form around the container.

It seems like you want some sort of htmlhelper function to generate that content. Have you looked into implementing it as a helper instead of a partial view?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!