How to update Model when binding to a ViewModel?

前端 未结 3 1495
予麋鹿
予麋鹿 2021-02-01 22:42

I have an [HttpPost] action method signature like this:

[HttpPost]
public ActionResult Edit(ExistingPostViewModel model)
{
   // Save the edited Pos         


        
相关标签:
3条回答
  • 2021-02-01 23:09

    I actually ran into this exact same issue in a project I'm currently working on. As much as I wasn't a fan of it, I ended up doing the left to right approach and manually mapping my viewmodel data back to my entity.

    The only nice thing about this approach is it does give you more control. Since I started using more compound viewmodels, where you actually have fields from more than one entity in your viewmodel, it started making more sense to do things this way.

    I'm also using AutoMapper, and you're absolutely right, it does get awkward when you're trying to do a simple update operation. Wish I had some super clever workaround for you, but the "old fashioned way" seems to get the job done best for the work I've been doing.

    0 讨论(0)
  • 2021-02-01 23:14

    Not sure if this will help, but it is working for me. I have my underlying domain table as a Visitor Object. My viewmodel contains the Visitor Object plus a couple of IEnumerables for dropdowns.

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id)
    
        {
            Visitor Visitor = new Visitor();
            Visitor = db.Visitors.FirstOrDefault(v => v.VisitorID == id);
    
            UpdateModel(Visitor, "Visitor");
    
            db.SaveChanges();
            return RedirectToAction("Index");
    
        }
    

    The UpdateModel works off my viewmodel because of the "Visitor" string telling it what values to compare.

    0 讨论(0)
  • 2021-02-01 23:17

    For simple things where you don't have to run any controls prior to implementing the update what you are doing is okay (db.get(), and then update).

    When things get complicated, you have to load the entity, and then select and apply user's changes from the view model, property by property. In those cases, you end up writing Update methods, which gets the new data as input, and then you load the existing entity, then compare states, and take the required actions based on the view model data. Actually in this case, probably you wont have an Update method but will have behaviors, like CancelPost, AddComment, EditPost (which also logs the edit reason), AddTagsToPost etc.

    0 讨论(0)
提交回复
热议问题