[RESOLVED]MVC 5 using mongodb update error

how to update in mvc using mongodb 

upsert option creates new insert 

[HttpPost]
        public ActionResult Edit(Mems item)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    item.UpdateDate = DateTime.UtcNow;
                    IMongoQuery query = Query.EQ("_id", item.Id);
                    //var savemem = context.mem.FindOne(query);
                    IMongoUpdate update = Update
                        .Set("fname", item.fname)
                        .Set("lname", item.lname)
                        
                        .Set("passw", item.passw)
                        .Set("bdate", item.bdate)
                        .Set("gender", item.gender)
                        .Set("mobile", item.mobile)
                        .Set("countryid", item.countryid)
                        .Set("stateid",item.stateid)
                        .Set("cityid",item.cityid)
                       
                        .Set("aboutme", item.aboutme)
                        .Set("UpdateDate", item.UpdateDate )                   
                        ;
                        
            

                    WriteConcernResult  result = context.mem.Update(query, update, UpdateFlags.None);
                   
                }
                else
                {
                    ModelState.AddModelError("", "Unable To Update Profile.");
                }
                var country = context.country.FindAll();
                
                var states = context.states.FindAll();
                var city = context.citytable.FindAll();
               
                ViewBag.countryid = new SelectList(country, "countryid", "countryname", item.countryid);
                ViewBag.stateid = new SelectList(states, "stateid", "statename",item.stateid);
                ViewBag.cityid = new SelectList(city, "cityid", "cityname",item.cityid); 
                return View(item);
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("", ex.Message );
                return View(item);
            }
        }

i m trying this code but not changing in db

pjpatil

i m trying this code but not changing in db

did different values send from UI to Mongo? If yes, then it is a problem with MongoDb code, not with MVC.

Hi pjpatil,

Thanks for your post.

Your code looked fine.

I guess that this problem is related to your database connectionstring,you’d better check it if correct.

There’s a  tutorial,you can refer to the following link:

http://www.joe-stevens.com/2011/10/02/a-mongodb-tutorial-using-c-and-asp-net-mvc/

Hope this can be helpful.

Best Regards,

Eileen

Leave a Reply