简体   繁体   English

为 ASP.NET MVC 视图准备模型

[英]Preparing models for ASP.NET MVC views

When returning strongly typed models for views such as Create and Edit (when validation of the object we are editing fails) I usually prepare the models like this:当为创建和编辑等视图返回强类型模型时(当我们正在编辑的 object 的验证失败时)我通常准备这样的模型:

    //
    // GET: /Invoice/Create
    public virtual ActionResult Create()
    {
        // prepare the empty model
        Invoice model = new Invoice();
        model.Client = new Client();
        model.Client.PostCode = new PostCode();
        return View(model);
    }

    //
    // POST: /Invoice/Create
    [HttpPost]
    public virtual ActionResult Create(Invoice document,
                                       FormCollection collection)
    {

        // check for errors
        if (!ViewData.ModelState.IsValid)
        {
            document.Client = new Client();
            document.Client.PostCode = new PostCode();
            return View(document);
        }

Now I know that this is how others do it too, in fact you can see this same approach in MVC Music Store sample and others.现在我知道其他人也是这样做的,实际上您可以在 MVC Music Store 示例和其他人中看到相同的方法。 However, this is very error prone because one might accidentally left out a referenced entity which is required in the view.但是,这很容易出错,因为可能会不小心遗漏了视图中所需的引用实体。 It also requires too much thinking about view/model interaction.它还需要过多考虑视图/模型交互。 What I would want is some sort of automatism.我想要的是某种自动化。 Value typed properties in models usually aren't the problem because they default either to zero or empty strings.模型中的值类型属性通常不是问题,因为它们默认为零或空字符串。 Reference types however should be initialized with new ..but sooner or later we end up with code blocks that are being repeated, reference type properties being left out, etc..And I don't think it's good coding practice either.然而,引用类型应该用new ..初始化。但迟早我们会得到重复的代码块,引用类型属性被遗漏等等。我也不认为这是一个好的编码实践。

What are other options we could take?我们还可以采取哪些其他选择?

UPDATE:更新:

Because replies kinda missed the point (they do not relief us of thinking about models in any way and require additional code in model classes), I was thinking if this option would work:因为回复有点错过了重点(它们不会让我们以任何方式思考模型,并且需要在 model 类中添加额外的代码),我在想这个选项是否可行:

  1. Use custom Action filter,使用自定义动作过滤器,
  2. override OnActionExecuted()覆盖OnActionExecuted()
  3. use Reflection inside this method to take out the object from the Model and enumerate its public properties and try to initialize them.在此方法中使用反射从 Model 中取出 object 并枚举其公共属性并尝试对其进行初始化。

I have steps 1, 2 and 3 partially implemented but I cannot figure out how to do "... = new Client();"我已经部分实施了步骤 1、2 和 3,但我无法弄清楚如何执行“... = new Client();” programatically with Reflection.以编程方式使用反射。

Make the properties of your model return a new instance if it is null使您的 model 的属性返回一个新实例,如果它是 null

private Client client;
public Client Client
{
  get
  {
    if (client == null)
      client = new Client();

    return client;
  }
}

I suggest that you use a Strongly typed view bound to a ViewModel that is distinct from the Domain Model you're trying to create, and put whatever necessary logic into the constructor of the ViewModel我建议您使用绑定到与您尝试创建的域 Model 不同的 ViewModel 的强类型视图,并将任何必要的逻辑放入 ViewModel 的构造函数中

I'm not sure I fully understand your question.我不确定我是否完全理解你的问题。 You want what automated?你想要什么自动化? ViewModels and Views?视图模型和视图? Are you creating strongly typed views?您是否正在创建强类型视图?

I have created a T4 template that I point to a database and it generates a ViewModel for every table.我创建了一个指向数据库的 T4 模板,它为每个表生成一个 ViewModel。 Foreign keys become drop down lists, long strings get a TextArea instead of TextBox, etc. I then delete the ones I don't need and modify the ones I want to keep.外键变成下拉列表,长字符串得到一个 TextArea 而不是 TextBox,等等。然后我删除我不需要的那些并修改我想要保留的那些。 It's not a totally automated process, but it does 80 to 90 percent of the work, depending upon the project.这不是一个完全自动化的过程,但它会完成 80% 到 90% 的工作,具体取决于项目。

Then I generate strongly typed Views from those ViewModels.然后我从这些 ViewModel 生成强类型视图。

It also sounds like you might be interested in AutoMapper .听起来您可能对AutoMapper感兴趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM