假设我们有这些简化的模型:
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;}
}
现在我们想为学生和老师创建一个创建页面。我的问题是我们如何利用继承的好处为学生和教师创建一个页面?
我试过了:
@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>
但不允许asp-for="((Student)Model).Grade"
答案 0 :(得分:3)
根据https://docs.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms#the-input-tag-helper &#34; @&#34; character可用于启动内联表达式
所以这是正确的:
item {
id: 1
name: '1'
}
item {
id: 2
name: '2'
}
item {
id: 3
name: '3'
}
item {
id: 4
name: '4'
}
item {
id: 5
name: '5'
}
item {
id: 6
name: '6'
}
item {
id: 7
name: '7'
}
item {
id: 8
name: '8'
}
item {
id: 9
name: '9'
}
item {
id: 10
name: '10'
}
item {
id: 11
name: '11'
}
答案 1 :(得分:0)
查看关于github的这个ViewModel with inheritance in ASP .NET Core讨论:
它建议了一个解决方案,其中subclass
标记助手围绕特定于每个子类的字段。如果模型为null或者传递了该类的特定子类,则会呈现这些字段。
以下是示例:link