简体   繁体   English

剃刀视图中的自定义模板

[英]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. 可以说模型包含一个具有Firstname和Lastname的Person对象。

The template would look like this witch I would write in the cshtml file 模板看起来像我在cshtml文件中写的这个女巫

<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 然后,我将创建一个HtmlHelper方法,该方法使用来自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. 但是简短的答案是,在某些情况下,我需要根据一些内部条件返回一些完全不同的html。 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. 我最终传入了@helper方法作为模板。 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. 这种方法提供了代码格式化,智能感知,可重用性,当然还有覆盖漏洞的能力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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