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

how to edit in asp.net mvc 5 using view model?


I have a problem with edit and details in MVC 5 I use ViewModel in my application and this is my ViewModel code:

public class HeadsViewModel
{
    public int h_id { get; set; }
    public string h_no { get; set; }
    public string titles { get; set; }
    public string h_initials { get; set; }
    public string fname { get; set; }
    public string lname { get; set; }
    public string email { get; set; }
    public string cell { get; set; }
    public string tel_h { get; set; }
    public int title_id { get; set; }
    public string flatName { get; set; }
    public string flatNo { get; set; }
    public string strname { get; set; }
    public string strNo { get; set; }
    public string suburb { get; set; }
    public string city { get; set; }
    public string tel_w { get; set; }
    public string fax { get; set; }
    public string cell2 { get; set; }
    public bool active { get; set; }
    public string province { get; set; }
    public string country { get; set; }
    public int postalcode { get; set; }
    public string zone { get; set; }
    public bool isHa { get; set; }
    public int addtype { get; set; }
}

Controller:

    [HttpGet]
    public ActionResult Edit(int? id)
    {
        var member = (from h in db.Members
                      join j in db.Contacts on h.m_id equals j.m_id
                      join x in db.Addresses1 on h.phys_addid equals x.PhysAddID
                      join f in db.Titles on h.title_id equals f.title_id
                      where h.m_id == id
                      select new
                      {
                          title_id = h.title_id,
                          memType_id=h.Memtype_Id,
                          marital_id = h.maritialid,
                          m_id = h.m_id,
                          initials = h.initial,
                          fname = h.fname,
                          lname = h.lname,
                          dob = h.dob,
                          active= h.Active,

                          religion = h.religion,
                          occupation = h.occupation,
                          company = h.company,
                          note = h.Note,

                          employed = h.employed,
                          reg = h.reg_date,
                          accnumb = h.AccNumb,

                          agegroup = h.AgeGrp,
                          email = j.Email,
                          cell = j.cell,
                          cell2 = j.cell2,
                          tel_w = j.tel_w,
                          tel_h = j.tel_h,
                          fax = j.fax,
                          flatno = x.flatNo,
                          flatname = x.flatName,
                          strname = x.strname,
                          strno = x.strNo,
                          suburb = x.Suburb,
                          city = x.City,
                          province = x.Province,
                          country = x.Country,

                          zone = x.zone,
                          postalCode = x.PostalCode,


                      }).First();

        var viewmodel = new MembersViewModel();

        viewmodel.title_id = member.title_id;
        viewmodel.maritialid = (int)member.marital_id;
        viewmodel.m_id = member.m_id;
        viewmodel.Memtype_Id = (int)member.memType_id;

        viewmodel.initial = member.initials;
        viewmodel.fname = member.fname;
        viewmodel.lname = member.lname;
        viewmodel.dob = member.dob;
        viewmodel.active = (bool)member.active;
        viewmodel.religion = member.religion;
        viewmodel.occupation = member.occupation;
        viewmodel.company = member.company;
        viewmodel.note = member.note;

        viewmodel.regdate = member.reg;
        viewmodel.accNumb = member.accnumb;

        viewmodel.agegroup = member.agegroup;
        viewmodel.email = member.email;
        viewmodel.cell = member.cell;
        viewmodel.cell2 = member.cell2;
        viewmodel.tel_h = member.tel_h;
        viewmodel.tel_w = member.tel_w;
        viewmodel.fax = member.fax;
        viewmodel.flatName = member.flatname;
        viewmodel.flatNo = member.flatno;
        viewmodel.strname = member.strname;
        viewmodel.strNo = member.strno;
        viewmodel.suburb = member.suburb;
        viewmodel.city = member.city;
        viewmodel.province = member.province;
        viewmodel.country = member.country;



        try
        {


            viewmodel.postalcode = (int)member.postalCode;
        }
        catch (Exception) { }
        ViewBag.MaritialType = new SelectList(db.Maritials, "Maritialid", "MaritialType", viewmodel.maritialid);
        ViewBag.Type = new SelectList(db.MemberTypes.ToList(), "Memtype_Id", "Type", viewmodel.Memtype_Id);

        ViewBag.Titles = new SelectList(db.Titles.ToList(), "title_id", "Titles", viewmodel.title_id);

        return View(viewmodel);


    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(MembersViewModel vm)
    {
           if (ModelState.IsValid)
        {



            var member = db.Members.Find(vm.m_id);
            var add = db.Addresses1.Find(vm.PhysAddID);
            var con = db.Contacts.Find(vm.m_id);






                member.title_id = vm.title_id;
                member.maritialid = (int)vm.maritialid;
                member.m_id = vm.m_id;
                member.Memtype_Id = (int)vm.Memtype_Id;

                member.initial = vm.initial;
                member.fname = vm.fname;
                member.lname = vm.lname;
                member.dob = vm.dob;
                member.Active = (bool)vm.active;
                member.religion = vm.religion;
                member.occupation = vm.occupation;
                member.company = vm.company;
                member.Note = vm.note;

                member.reg_date = vm.regdate;
                member.AccNumb = vm.accNumb;

                member.AgeGrp = vm.agegroup;



                con.Email = vm.email;
                con.cell = vm.cell;
                con.cell2 = vm.cell2;
                con.tel_h = vm.tel_h;
                con.tel_h = vm.tel_w;
                con.fax = vm.fax;
                add.flatName = vm.flatName;

                add.flatNo = vm.flatNo;
                add.strname = vm.strname;
                add.strNo = vm.strNo;
                add.Suburb = vm.suburb;
                add.City = vm.city;
                add.Province = vm.province;
                add.Country = vm.country;

                try
                {


                    add.PostalCode = (int)vm.postalcode;
                }
                catch (Exception) { }
                ViewBag.MaritialType = new SelectList(db.Maritials, "Maritialid", "MaritialType", vm.maritialid);
                ViewBag.Type = new SelectList(db.MemberTypes.ToList(), "Memtype_Id", "Type", vm.Memtype_Id);

                ViewBag.Titles = new SelectList(db.Titles.ToList(), "title_id", "Titles", vm.title_id);
                db.Entry(member).State = EntityState.Modified;
                db.Entry(add).State = EntityState.Modified;
                db.Entry(con).State = EntityState.Modified;

                db.SaveChanges();


                return RedirectToAction("Index");

        }

        return View(vm);

}

View:

@model parishV3.Model.HeadViewModel

My problem is that I want to use view model on my edit code and details code not tables. Please can you assist me with the code.

Now Get edit Code is working , but the problem is Post edit code is not work can you please help.


Solution

  • May help, try the below.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Head head)
    {
        if (ModelState.IsValid)
        {
            db.Entry(head).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    //Use automapper to map the objects or assign the data as below                 
        HeadViewModel headViewModel = new HeadViewModel {
        // Assign the property value from the table object 
        };
        ViewBag.title_id = new SelectList(db.Titles, "title_id", "Titles", head.title_id);
        return View(headViewModel);
    }
    
    [HttpGet]
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Head head = db.Heads.Find(id);
        if (head == null)
        {
            return HttpNotFound();
        }
    
    //Use automapper to map the objects or assign the data as below                 
    HeadViewModel headViewModel = new HeadViewModel {
        // Assign the property value from the table object
        };
        return View(headViewModel);
    }
    

    To use three different tables you must modify your viewModel like,

    public class HeadViewModel
    {
        public Table1 Table1 { get; set; }
        public Table2 Table2 { get; set; }
        public Table3 Table3 { get; set; }
    }
    
    public class Table1
    {
        public int column1 { get; set; }
    
        public string column2 { get; set; }
    }
    
    public class Table2
    {
        public int column1 { get; set; }
    
        public string column2 { get; set; }
    }
    
    public class Table3
    {
        public int column1 { get; set; }
    
        public string column2 { get; set; }
    }
    

    While binding the data in the controller do as following,

            HeadViewModel headViewModel = new HeadViewModel
            {
                Table1 = new Table1
                {
                    column1 = 0, // you data from the DB table object
                    column2 = ""// you data from the DB table object
                },
                Table2 = new Table2
                {
                    column1 = 0, // you data from the DB table object
                    column2 = ""// you data from the DB table object
                },
                Table3 = new Table3
                {
                    column1 = 0, // you data from the DB table object
                    column2 = ""// you data from the DB table object
                }
            };
            return View(headViewModel);
    

    Updated
    It seems you are returning 3 view models on post method which certainly not possible whereas you must use the view model that was binded to the view.

    The view model that was binded to the view 'Edit' is 'MembersViewModel' so your Post action method should look like,

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(MembersViewModel members)
    {
       // From here you may want to again map the data from MembersViewModel to the table objects and do the rest of operation as you have done below
       // 1. Get the data table objects
       // 2. Assign the data from the MembersViewModel to the respective data tables which is similarly done in [HttpGet] method.
       // 3. Then save the changes as below.
            db.Entry(member).State = EntityState.Modified;
            db.Entry(add).State = EntityState.Modified;
            db.Entry(con).State = EntityState.Modified;
            db.SaveChanges();
    }
    

    Updated Oct 20 Instead of writing,

    db.Entry(member).State = EntityState.Modified;
    

    try the below,

    db.EntityClass.Attach(member);
    db.ObjectStateManager.ChangeObjectState(member, EntityState.Modified);
    

    here EntityClass is the class that is generated automatically for the member. And do the same for the other tables too.