Search code examples
c#asp.net-mvcparametersasp.net-mvc-viewmodel

How can I add a database entry using a viewmodel?


I am making a page that will contains several dropdowns and a few textboxes. I have the data being stored in a viewmodel, that is then passed back to my [HttpPost] create method.

I am fairly new to viewmodels, and am wondering how to add a new database entry using data from a viewmodel.

When I go into Debug mode, all my viewmodel entities are populated, but MVC is not making the connection to make a new entry with those values. Current [Post] create method.

    [HttpPost]
    public ActionResult Create(OrdersViewModel vmobj)
    {
        if (ModelState.IsValid)
        {
            order obj = new order();
            obj.projectNumber=vmobj.projectID.ToString();
            obj.testingPhase = vmobj.testPhaseSt;
            obj.unitSerial = vmobj.unitSerialSt;
            obj.completeDate = vmobj.completeDate;
            obj.closingStatement = vmobj.closingStatement;

            db.orders.Add(obj);


            return RedirectToAction("Create");
        }

        return View();
    }

Solution

  • You need to call the DbContext.SaveChanges() to apply the changes in the database. Just like Jeroen told you.