你怎么去处理涉及复杂的类型时,Ajax和模型绑定?你怎么、绑定、模型、复杂

2023-09-10 18:24:52 作者:我是叼男M@N!

我想继续做模型,从我的观点Ajax调用时绑定。我使用 jQuery的AJAX 打的电话,而只是作为一个示例 - 这是我的控制器的方法我想从AJAX调用:

I would like to keep model binding when doing ajax calls from my view. I'm using jquery ajax to make the calls, and just as an example- this is my controller method I want to call from ajax:

public ActionResult Create(Person personToCreate) {
    //Create person here
}

正如你所看到的,这种方法是依靠模型绑定。这使得该方法变得更干净......但是,这意味着当AJAX进行呼叫时,它必须提供一切都不可为空的DB变量。

As you can see, this method is relying on Model Binding. This makes the method a lot cleaner... however, this means that when the ajax makes a call, it must supply all variables that are non-nullable in the DB.

所以,如果我有一个名为表有变量:

So, if I have a table called Person that has variables:

firstName varchar(25) not-null
lastName  varchar(25) not-null
myPet     int         not-null <-- This is a foreign key

那么实体框架类,,创建将类似于:

public class Person {
   public string firstName { get; set; }
   public string lastName { get; set; }
   public Pet myPet { get; set; }
}

由于没有变量可以为空(如在数据库中指定),这意味着Ajax调用必须提供一个字符串的firstName 字符串的lastName 宠物myPet 。但是JavaScript不能提供宠物...​​

Since none of the variables can be null (as specified in the DB) this means the ajax call must supply a string firstName, string lastName, Pet myPet. But javascript cannot supply the Pet...

所以,我只有两个选择(据我所知):

So I only have two options (that I know of):

允许myPet是在DB空

Allow myPet to be null in the DB

创建一个重新presents一个人,不需要的宠物对象奉承级...

Create a "flatter" class that represents a Person that doesn't require the pet object...

例如:

public class SimplePerson {
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string myPetName { get; set; }
}

第一个选项的问题是,它似乎很奇怪,必须修改数据库...绝对的东西错了,因为它是允许的东西它不应该​​是......

The problem with the first option is that it seems odd to have to modify the DB... definitely something wrong about it because it's allowing things it shouldn't be...

与第二个选项的问题是,我有很多的类,它似乎广泛被写重复的课程,每一个只是为了避免这种情况......如果我有30个教学班,这将是30的重复类,我必须创建,以允许对模型绑定

The problem with the second option is that I have a lot of classes and it seems extensive to be writing duplicate classes for each one just to avoid this... If I had 30 classes, that would be 30 duplicate classes that I would have to create in order to allow for model binding.

谁能想到什么更好的选择,或者放弃推理,为什么其中一个方案是优于其他?

Can anyone think of any better options, or give reasoning on why one option would be better than the other?

推荐答案

这里真正的技巧是您的视图模型类与实际模型类分开。视图模型类往往是有点简单,你需要做实际的东西与他们之前将它们映射回您的实际模型类。像AutoMapper工具使这个pretty的多,虽然易如反掌。

The real trick here is to separate your view model classes from the actual model classes. The view model classes tend to be a bit simpler, and you need to map them back into your actual model classes before doing real stuff with them. Tools like AutoMapper make this pretty much a snap though.