【发布时间】:2016-01-21 00:02:35
【问题描述】:
我正在构建一个项目,其中包含许多关于剃刀视图的通用代码。
例子:
<div class="form-group">
@Html.LabelFor(model => model.LayoutFrontAmount, htmlAttributes: new { @class = "control-label col-xs-12 col-sm-4 col-md-3" })
<div class="col-xs-4 col-sm-2 col-md-2 col-lg-1">
@Html.EditorFor(model => model.LayoutFrontAmount, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="col-xs-12 col-md-8 col-sm-offset-4 col-md-offset-3">
<span class="help-block">@Html.ValidationMessageFor(model => model.LayoutFrontAmount, "", new { @class = "text-danger" })</span>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LayoutFrontBackAmount, htmlAttributes: new { @class = "control-label col-xs-12 col-sm-4 col-md-3" })
<div class="col-xs-4 col-sm-2 col-md-2 col-lg-1">
@Html.EditorFor(model => model.LayoutFrontBackAmount, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="col-xs-12 col-md-8 col-sm-offset-4 col-md-offset-3">
<span class="help-block">@Html.ValidationMessageFor(model => model.LayoutFrontBackAmount, "", new { @class = "text-danger" })</span>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LayoutTRC, htmlAttributes: new { @class = "control-label col-xs-12 col-sm-4 col-md-3" })
<div class="col-xs-4 col-sm-2 col-md-2 col-lg-1">
@Html.EditorFor(model => model.LayoutTRC, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="col-xs-12 col-md-8 col-sm-offset-4 col-md-offset-3">
<span class="help-block">@Html.ValidationMessageFor(model => model.LayoutTRC, "", new { @class = "text-danger" })</span>
</div>
</div>
唯一改变的是模型的属性。
有没有办法将所有代码替换为:
@TemplateName1(model => model.LayoutFrontAmount)
@TemplateName1(model => model.LayoutFrontBackAmount)
@TemplateName1(model => model.LayoutTRC)
【问题讨论】:
-
您可以创建一个 HtmlHelper 扩展方法来生成标签、表单控制和验证消息(以及相关的
div元素),您可以将其用作(例如)@Html.MyEditorFor(model => model.LayoutFrontAmount) -
谢谢@StephenMuecke,但我更喜欢最接近和更干净的 HTML 结构,它看起来很难理解和理解是什么
-
抱歉,不确定您的意思。创建扩展方法后,您在视图中只需要 3 行代码 (
@Html.MyEditorFor(m => m.someProperty)) 即可生成与您在问题中显示的完全相同的所有 html -
就像@Chase 的回答一样,我可以查看视图并查看 HTML 结构
标签: c# asp.net-mvc razor