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

1

1

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?

Risotto answered 16/7, 2009 at 14:42 Comment(0)
G
2

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.

Godevil answered 16/7, 2009 at 16:56 Comment(2)
"separate your view model classes from the actual model classes" so you're saying I should have simplified duplicates of each class?Risotto
Yup, dumbed down classes for mapping in and out of forms and such.Godevil

© 2022 - 2024 — McMap. All rights reserved.