'Referencing Razor field objects to factor C# (MS-MVC 5)
I'm trying to factor field references in Razor code (.cshtml) to one spot so that they are easier to change and copy. But it's not working. It thinks the "fieldRef" object is the field itself such that the label reads "fieldRef" on the output.
@{object fieldRef = null; }
<div class="col-md-4">
@{ fieldRef = Model.ExcludeWords;}
@Html.LabelFor(Model => fieldRef, htmlAttributes:
new { @class = "control-label", @style = "color:#004400" })
@Html.EditorFor(Model => fieldRef,
new
{
htmlAttributes = new
{
@class = "form-control"
}
})
@Html.ValidationMessageFor(Model => fieldRef, "", new { @class = "text-danger" })
</div>
@* More fields to follow this pattern... *@
Note that "fieldRef" is referenced 3 times. The problem is not a show-stopper, but if I can get references working, I can simplify a heck of a lot of coding tasks.
Solution 1:[1]
In ASP.NET Core Razor Pages, I replaced the following:
<dl class="row">
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Course.Title)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Course.Title)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Course.Credits)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Course.Credits)
</dd>
<dt class="col-sm-2">
@Html.DisplayNameFor(model => model.Course.Department)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(model => model.Course.Department.DepartmentID)
</dd>
</dl>
with:
<dl class="row">
@{
await Template1(model => model.Course.CourseID);
await Template1(model => model.Course.Title);
await Template1(model => model.Course.CourseID);
await Template2(model => model.Course.Department, model => model.Course.Department.DepartmentID);
}
</dl>
where Template1 and Template2 are defined at the top of the file:
@{
async Task Template1<T>(Expression<Func<DeleteModel, T>> expr)
{
<dt class="col-sm-2">
@Html.DisplayNameFor(expr)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(expr)
</dd>
}
async Task Template2<T1, T2>(Expression<Func<DeleteModel, T1>> expr_a, Expression<Func<DeleteModel, T2>> expr_b)
{
<dt class="col-sm-2">
@Html.DisplayNameFor(expr_a)
</dt>
<dd class="col-sm-10">
@Html.DisplayFor(expr_b)
</dd>
}
}
Mentioning this as an example of passing around expressions, which it seems you're aiming to do.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dharmatech |
