简体   繁体   中英

Custom template in razor view

I am trying to apply some custom templating to a razor view. It is a bit special so here is an example.

Lets say out model contains a Person object with Firstname and Lastname.

The template would look like this witch I would write in the cshtml file

<div data-template-id="testTemplate" data-template-model="@Model.Person">
<span>{{Firstname}}</span>
<span>{{Lastname}}</span>
</div>

I would then make a HtmlHelper method that populates the template with data from Model.Person

So har I have got the access to the data but I am no sure how to access the view and get the template.

public static MvcHtmlString Test<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression){
    var model = html.ViewData.Model;
        string propName = "";
        if (expression.Body is MemberExpression)
            propName = ((MemberExpression)expression.Body).Member.Name;
        var value = model.GetType().GetProperty(propName).GetValue(model, null);
        // TODO: get template and insert data from model
        return new MvcHtmlString($"<div>{value}</div>");
}

I know it is a bit strange why I would do this. But the short answer is that in some conditions I need to return some completly different html, based on some internal conditions. In which case I would just remove the template completely.

I found a solution to this problem me self. I ended up passing in a @helper method as template. Like this

public static MvcHtmlString Test<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
    var someCondition = false;

    if (someCondition)
    {
       // Return some domain specific html.
       return new MvcHtmlString("<div></div>");
    }
    else
    {
        var result = expression.Compile();

        TModel model = html.ViewData.Model;

        var value = result(model);

        var r = new MvcHtmlString(value.ToString());
        return r;
    }
}

I would then use it like this:

@Html.Test(p => ImageTemplate(p.Avater))
@helper ImageTemplate(Picture avater)
{
    <h1 style="color: red">@avater.Title</h1>
    <h5>@avater.Url</h5>
}

This method provides code formatting, intellisense, reusability and of course, the ability to override the hole thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM