Can I somehow take string values from a class and insert those string values into the values of the asp-for
property of a Razor Page HTML element?
I have a class like below that just contains the names of the Days of the Week:
public class Days
{
[BindProperty]
public static List<string> DaysList { get; set; } = new List<string>
{
new string("Saturday"),
new string("Sunday"),
new string("Monday"),
new string("Tuesday"),
new string("Wednesday"),
new string("Thursday"),
new string("Friday")
};
}
I want to be able to dynamically use the names of the week to build out asp-for
values that are actual var/property names. Like in asp-for="@(Day)StartTime"
, it would actually be a variable in the code behind named SaturdayStartTime
, SundayStartTime
, etc. Then for @SpanHours
the same would apply there as a property of MyObject
which is MyObject.SaturdaySpanHours
, MyObject.SundaySpanHours
, etc.
I was just hoping to be able to implement it via foreach like below, but that doesn't work.
<div>
@{
foreach (string Day in Days.DaysList)
{
string SpanHours = "MyObject." + Day + "SpanHours";
<input type="time" value="@Model.MyObject.@(Day)StartTime.ToString("HH:mm")" asp-for="@(Day)StartTime" />
<input asp-for="@SpanHours" class="form-control" value=@Model.MyObject.@(Day)SpanHours />
}
}
</div>
Is there another method to be able to dynamically insert values into the asp-for
properties?
Don't use asp-for
; instead, use name
and id
:
<input name="@SpanHours" id="@SpanHours" class="form-control" value=@Model.MyObject.@(Day)SpanHours />