gpt4 book ai didi

c# - MVC View 模型继承和创建操作

转载 作者:太空狗 更新时间:2023-10-29 22:22:24 24 4
gpt4 key购买 nike

我正在努力找出在 MVC 应用程序中处理模型类型层次结构的最佳架构。

给定以下假设模型 -

public abstract class Person
{
public string Name { get; set; }
}

public class Teacher : Person
{
public string Department { get; set; }
}

public class Student : Person
{
public int Year { get; set; }
}

我可以为每种类型创建一个 Controller 。 Person 将只有 index 和 detail 操作以及使用显示模板的 View ,Teacher 和 Student 将只有 Create/Edit 操作。这会起作用,但看起来很浪费,而且不会真正扩展,因为如果将另一种类型添加到层次结构中,将需要一个新的 Controller 和 View 。

有没有办法在 Person Controller 中创建更通用的创建/编辑操作?我已经搜索了一段时间的答案,但似乎无法准确找到我正在寻找的内容,因此我们将不胜感激 :)

最佳答案

当然可以,但这需要一点腿力。

首先,在您的每个编辑/创建 View 中,您需要发出您正在编辑的模型类型。

其次,您需要为 person 类添加一个新的模型绑定(bind)器。以下是我为什么要这样做的示例:

public class PersonModelBinder :DefaultModelBinder
{

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
PersonType personType = GetValue<PersonType>(bindingContext, "PersonType");

Type model = Person.SelectFor(personType);

Person instance = (Person)base.CreateModel(controllerContext, bindingContext, model);

bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instance, model);

return instance;
}

private T GetValue<T>(ModelBindingContext bindingContext, string key)
{
ValueProviderResult valueResult =bindingContext.ValueProvider.GetValue(key);

bindingContext.ModelState.SetModelValue(key, valueResult);

return (T)valueResult.ConvertTo(typeof(T));
}
}

在你的应用开始注册它:

ModelBinders.Binders.Add(typeof(Person), new PersonModelBinder());

PersonType 是我倾向于在每个模型中使用的,它是一个枚举,说明每种类型是什么,我在 HiddenFor 中发出它,以便它与发布数据一起返回。

SelectFor 是一种返回指定枚举类型的方法

public static Type SelectFor(PersonType type)
{
switch (type)
{
case PersonType.Student:
return typeof(Student);
case PersonType.Teacher:
return typeof(Teacher);
default:
throw new Exception();
}
}

你现在可以在你的 Controller 中做这样的事情

public ActionResult Save(Person model)
{
// you have a teacher or student in here, save approriately
}

Ef 能够通过 TPT 样式继承非常有效地处理这个问题

只是为了完成示例:

public enum PersonType
{
Teacher,
Student
}

public class Person
{
public PersonType PersonType {get;set;}
}

public class Teacher : Person
{
public Teacher()
{
PersonType = PersonType.Teacher;
}
}

关于c# - MVC View 模型继承和创建操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25186901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com