2

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"

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

0

Look into this ViewModel with inheritance in ASP .NET Core discussion on github:

It suggests a solution where a subclass tag-helper surround the fields that are specific to each subclass. That fields are rendered either if the model is null or if a specific subclass of that class is passed.

Here is the example: link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.