有没有办法创建自定义 MVC Razor 元素,例如 "text" ?



我想创建一个像<text></text>这样的自定义剃刀标记,以决定如何处理其中的html代码。有什么方法可以创建像<text></text>这样的剃刀元素并将其添加到剃刀引擎中吗?

我不想为此创建任何HtmlHelper

对于Examle:

<WYSYWIG>
Hello There!
</WYSYWIG>

<WeatherChart City="NY">
</WeatherChart>

解释:

这个想法是让服务器标签通过赋予它们的属性转换(解析)为html代码。这类代码有助于初级开发人员避免涉及控件的复杂性。

与您所描述的内容最接近的是创建显示或编辑器模板。然后可以为模型定义模板,并将其与视图中的@Html.DisplayFor()一起使用。

这里有一篇很好的博客文章,可以让你开始使用aspnetmvc显示和编辑器模板,并快速概述下面的结构。

示例

型号-WeatherChartModel.cs

public class WeatherChartModel 
{
}

显示模板-WeatherChart.cshtml

<div class="weather-chart">
   // Some other stuff here
</div>

视图-Index.chtml

@model WeatherChartModel
@Html.DisplayForModel() // This will output the template view for the model

为了在razor中创建自定义元素处理,例如<text>,您需要实现一个自定义System.Web.Razor.dll(负责解析文档)。具体来说,您希望重新实现的类将是System.Web.Razor.Parser.HtmlMarkupParser

然而,考虑到框架本身的灵活性,我认为这是没有必要的。如果你想保持模块化,可以考虑使用DisplayTemplates/EditorTemplates,或者考虑编写自己的扩展方法。例如,以下任何一种都更理想:

@* TextField is decorated with UIHint("WYSIWYG"), therefore
   calling ~/Views/Shared/EditorTemplates/WYSIWYG.cshtml *@
@Html.EditorFor(x => x.TextField)
@* WeatherField is decorated with UIHint("WeatherChart"), therefore
   calling ~/Views/Shared/DisplayTemplates/WeatherChart.cshtml *@
@Html.DisplayFor(x => x.WeatherField)

或者:

@* Custom extension method *@
@Html.WysiwygFor(x => x.TextField)
@* Another custom extension method *@
@Html.WeatherChartFor(x => x.WeatherField)

相关内容

最新更新