I am building a project with a lot of common code regarding the razor view.
Example:
<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>
The only thing that changes is the Model's property.
Is there a way to replace all the code with something like:
@TemplateName1(model => model.LayoutFrontAmount)
@TemplateName1(model => model.LayoutFrontBackAmount)
@TemplateName1(model => model.LayoutTRC)
Depends on what the types are for each of LayoutFrontAmount, LayoutFrontBackAmount, and LayoutTRC. Are these all strings? If so, you could have a common view file that stores the template for displaying each, and then display each of them by using
@Html.Partial()
in your primary view:MyView.cshtml
And then in your main view file you could render each of LayoutFrontAmount, LayoutFrontBackAmount, and LayoutTRC as follows:
If they are different types, that poses a bigger challenge.
You can create a HtmlHelper extension method that will generate all the html for a property, including the label and input element
Then you can register this in your
web.config
file (means you do not need@using ...
in the viewNow in your main view your can generate all the html shown in your question with just the following 3 lines of code
And if you want this to be reusable across multiple projects, compile it in separate dll and add a reference to it in your projects.