我正在.Net MVC 项目中开发一个创建表单。我将为这个问题创建一个简单的演示,尽可能接近我的真实业务场景。
我有一个人类和几个从它继承的其他类。
public class Person
{
public int Id { get; set; }
[Required]
public string Forename { get; set; }
[Required]
public string Surname { get; set; }
[Required]
public DateTime Dob { get; set; }
}
public class Teacher: Person
{
[Required]
public string Department { get; set; }
}
public class Student: Person
{
[Required]
public string TermAddress { get; set; }
}
如果我有如下创建的 Action 方法。
public class PersonController : Controller
{
public ActionResult Create()
{
var personFactory = new PersonFactory();
var p = personFactory.CreatePerson("student");
return View(p);
}
}
public class PersonFactory
{
public object CreatePerson(string type)
{
switch(type)
{
case "teacher":
return new Teacher();
break;
case "student":
return new Student();
break;
default:
return null;
break;
}
}
}
是否有可能有一个可以处理这两种情况的视图?在我的业务案例中,有 10 多种不同类型的类似类,我想知道是否有一种方法可以在不创建 10 多个视图的情况下解决问题。我知道我已经强烈输入了视图,但没关系。只要我可以使用一个视图,我就可以拥有 10 多个视图模型。欢迎任何我可以解决此类问题的替代建议或方法。谢谢。
@{
????????????? just an idea .. something like that .. ???????????
var type = "student";
if(type == "stuent")
{
@model WebApplication1.Models.Student
}
else if(type == "teacher")
{
@model WebApplication1.Models.Teacher
}
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.EditorForModel()
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}