How to cast an object inside the quotes("") (asp-for="object") in the page view?
I have a parent class Person and two child classes Student and Teacher.
variable:
Person person;
I want to cast it to behave as the child class.. something like:
asp-for="(Person)person.grade"
or
asp-for="((Person)person).grade"
But neither code works. How can I cast an object inside of asp-for quotes ("")?
CodePudding user response:
<input asp-for="...."/>
The input tag helper binds a ModelExpression
property to the attribute. ModelExpressions are a bit weird. Essentially, the razor compiler translates your code into something equivalent to;
= ModelExpressionProvider.CreateModelExpression<TModel>(m => m.[your attribute text], ...);
However, if your attribute starts with a @
, that leading m.
is not inserted. In other words, you should be able to do the following;
<input asp-for="@(Person)Model.person.grade" />
At least that should compile. Whether that solves your actual problem is another matter.
CodePudding user response:
This is the whole code structure:
//parent class
public abstract class Person
{
//code
}
//child class
public class Teacher : Person
{
//code
public double Salary { get; set; }
}
//2nd child class
public class Student : Person
{
//code
public double Grade { get; set; }
}
//in WinForms I could access child classes components by down casting
public partial class FormSchool : Form
{
//code
Person Person;
double grade = ((Student)Person).Grade;
//code
}
//in razor pages as well in .cs files
public class IndexModel : PageModel
{
//code
[BindProperty]
public Person Person { get; set; }
//code
}
//but when it came to the page templates I got stuck how to do it inside of the asp-for=".." quotes
// the following code doesn't work
<select asp-for="((Student)Person).Grade" asp items="Html.GetEnumSelectList<Grades>()"></select>
neither this:
<input asp-for="@(Person)Model.person.grade"/>
For now I am just using child class to create objects and modelBinding them to the view, but I would like to just have one object and cast it regarding some specific child class uses... in the templates.