Let's say we have these simplified models:
public class Person {
public string Address {set;get;}
}
public class Student: Person {
public float Grade {set;get;}
}
public class Teacher: Person {
public string Department {set; get;}
}
Now we want to have a create page for student and teacher. my question is how we can use benefits of inheritance to create only one page for student and teacher?
I tried this:
@model Person
@{
bool isStudent = Model is Student;
}
<form asp-action="Create">
<div class="form-horizontal">
@if (isStudent)
{
<div class="form-group">
<label asp-for="((Student)Model).Grade" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="((Student)Model).Grade" class="form-control" />
<span asp-validation-for="((Student)Model).Grade" class="text-danger"></span>
</div>
</div>
} else {
<div class="form-group">
<label asp-for="((Teacher)Model).Department" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="((Teacher)Model).Department" class="form-control" />
<span asp-validation-for="((Teacher)Model).Department" class="text-danger"></span>
</div>
</div>
}
<div class="form-group">
<label asp-for="Address" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
</form>
but it does not allow asp-for="((Student)Model).Grade"
found it:
According to https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms#the-input-tag-helper "@" character can be used to start an inline expression
So this is correct:
asp-for="@(Model as Student).Grade"