how do you go about dealing with ajax and Model Binding when complex types are involved?

允我心安 提交于 2019-12-10 11:34:45

问题


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
}

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

Then the Entity Framework class, Person, created would be similar to:

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

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):

  1. Allow myPet to be null in the DB

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

ie:

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...

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?


回答1:


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.



来源:https://stackoverflow.com/questions/1138115/how-do-you-go-about-dealing-with-ajax-and-model-binding-when-complex-types-are-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!