Sven van den Boogaart
Sven van den Boogaart

Reputation: 12323

MVC 4 Pass Object

In my project I have a model

      Product (int int, String description, decimal price)

I also have another model

       Order (int id, virtual Product product, String customerName)

By adding the virtual before product, the product is a foreign key. I want to be able to place an order but how can I pass the objects product to the form of placing an order.

Lets say the user first selects a product from a list by clicking on a button buy, after that he has to enter his name (to keep it simple). How should I add the product to the enter your name form ?

I tried to add it manualy to my post handler (from the add name form after selecting a product) by using "

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Order order)
    {
        order.ConnectedProduct = db.Products.Find(1);
        if (ModelState.IsValid)
        {
            db.Orders.Add(order); 
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(order);
    }

but this still will return the field ConnectedProduct is required. (debbuging shows there is a product selected)

Upvotes: 0

Views: 54

Answers (1)

AlexC
AlexC

Reputation: 10756

The ModelState holds the state of the running the ModelBinder which happens earlier in the pipeline. So the ModelState.IsValid is showing you the results of the model binding + validation which happens earlier than the code that is executing in your controller. The fact that you set the state of the objects to being valid by adding a product does not change the previous result.

I would suggest that you create a View Model (different from your Domain Model) to be passed to and from the controllers and views which then can be mapped to a Domain Model in the controller. There are some useful tools to do a lot of the mapping for you to reduce boiler plate code. Popular options (in no other order than alphabetical) are Automapper and ValueInjecter.

Upvotes: 1

Related Questions