[RESOLVED]"ID" of inserted/updated always 0

Hello

I’m having an edit view where I create and update users. After it’s been saved I redirect to a detailsview, where I have a link "Edit User", and that UserID there for the link is always 0.

Why doesnt the object get the newly inserted id, or have the existing one passed on to detailsview?

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UserEdit([BindAttribute(Include = "Firstname,Surname,Username,Email,Password")]User user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    us.SaveUser(user);
                }
                catch
                {
                    ModelState.AddModelError("SomeError", "errrrrrrrrror");
                }
            }


            return View("UserDetail", new UsersAdminModel { User = user });
        }

 

and SaveUser in my “datalayer” looks like:

 

        public void SaveUser(User userobj)
        {
            User uo = _db.Users.Where(x => x.UserID == userobj.UserID).SingleOrDefault();

            bool NewUser = false;

            if (uo == null)
            {
                uo = new User();
                NewUser = true;
            }

            if (userobj.Datecreated == null)
            {
                userobj.Datecreated = DateTime.Now;
            }

            if (userobj.Lastmodified == null)
            {
                userobj.Lastmodified = DateTime.Now;
            }

            uo.Firstname = userobj.Firstname;
            uo.Surname = userobj.Surname;
            uo.Email = userobj.Email;
            uo.Username = userobj.Username ?? userobj.Email;
            uo.Datecreated = userobj.Datecreated;
            uo.Lastmodified = userobj.Lastmodified;
            uo.Password = userobj.Password;
            uo.UsersUsergroups = userobj.UsersUsergroups;

            if (NewUser)
                _db.Users.InsertOnSubmit(uo);

            _db.SubmitChanges();
        }

And in my detailsview I have a link:

 <%=Html.ActionLink("Edit User", "UserEdit", new { userID = Model.User.UserID }) %> |

and that link always have ?userID=0

/S 

Svevarn

After it’s been saved I redirect to a detailsview

I don’t see redirection in code you provided…

Add this after your call to _db.SubmitChanges:

if (NewUser)
    userobj.UserID = uo.UserID;

Tried that but that didnt change the value 

How u r passing the Model in the View. This will help us to understand why id is not going in the view.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using BookingSystem.Services;
using BookingSystem.Data;
using BookingSystem.MVC.Helpers;




namespace BookingSystem.MVC.Controllers
{
    public class UsersAdminModel
    {
        public IEnumerable<User> Users { get; set; }
        public User User { get; set; }


        public UsersAdminModel()
        {


        }


    }




    [HandleError]
    public class UsersAdminController : Controller
    {


        UsersService us = new UsersService();
        

        //
        // GET: /UsersAdmin/


        public ActionResult Users(int? page)
        {
            const int pagesize = 10;


            var pagnatedUsers = new PaginatedList<User>(us.GetUsers(), page ?? 0, pagesize);


            return View("Users", new UsersAdminModel { Users = us.GetUsers() });
        }




        public ActionResult UserDetail(int userID)
        {
            User u = us.GetUsers(userID).SingleOrDefault();


            if (u == null)
                return View("NotFound");


            return View("UserDetail", new UsersAdminModel { User = u });
        }




        public ActionResult UserEdit(int? userID)
        {
            User u;


            if (userID == null)
            {
                u = new User();
            }
            else
            {
                u = us.GetUsers(userID.Value).SingleOrDefault();
            }
            

            return View("UserEdit", new UsersAdminModel { User = u });
        }




        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UserEdit([BindAttribute(Include = "Firstname,Surname,Username,Email,Password")]User user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    us.SaveUser(user);
                }
                catch
                {
                    ModelState.AddModelError("SomeError", "errrrrrrrrror");
                }
            }


            return View("UserDetail", new UsersAdminModel { User = user });
        }


    }
}

 

 

Now I see another problem……… it ALWAYS adds a new User, and never edits for some reason :S 

Svevarn

Now I see another problem……… it ALWAYS adds a new User, and never edits for some reason :S 

Reason is 

Svevarn

 public ActionResult UserEdit([BindAttribute(Include = "Firstname,Surname,Username,Email,Password")]User user)  

U r telling Model binder to update the User object only with these fields and it does not include UserId. Without userId ur UserService assumes it as new user and adds it instead of updating the old user. and the reason u r getting blank user id  is that
u might not updating the user.UserId in ur UserService after updating the user. Remember that if ur setting the user variable(passed to us.SaveUser) to any other instance of user in the SaveUser method then setting this new instance is of no use as u have
lost the referenced object. Check ur SaveUser code or paste it so I can take a better look on what is going on

 I added UserID and now it works editing, and the detailsview shows the right UserID in the link.

Although the problem still persists in creating a new User.

 

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UserEdit([BindAttribute(Include = "Firstname,Surname,Username,Email,Password,UserID")]User userobj)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    us.SaveUser(userobj);
                }
                catch
                {
                    ModelState.AddModelError("SomeError", "errrrrrrrrror");
                }
            }


            return View("UserDetail", new UsersAdminModel { User = userobj });
        }

 

 

 

        public void SaveUser(User userobj)
        {
            User uo = _db.Users.Where(x => x.UserID == userobj.UserID).SingleOrDefault();

            bool NewUser = false;

            if (uo == null)
            {
                uo = new User();
                NewUser = true;
            }

            if (userobj.Datecreated == null)
            {
                userobj.Datecreated = DateTime.Now;
            }

            if (userobj.Lastmodified == null)
            {
                userobj.Lastmodified = DateTime.Now;
            }

            uo.Firstname = userobj.Firstname;
            uo.Surname = userobj.Surname;
            uo.Email = userobj.Email;
            uo.Username = userobj.Username ?? userobj.Email;
            uo.Datecreated = userobj.Datecreated;
            uo.Lastmodified = userobj.Lastmodified;
            uo.Password = userobj.Password;
            uo.UsersUsergroups = userobj.UsersUsergroups;

            if (NewUser)
            {
                userobj.UserID = uo.UserID;
                _db.Users.InsertOnSubmit(uo);                
            }

            _db.SubmitChanges();

            
        }

 

 

and in my userservice I have:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BookingSystem.Data;

namespace BookingSystem.Services
{
    public class UsersService
    {
        UserRepository _repository = new UserRepository();

        /// <summary>
        /// Returns all Users
        /// </summary>
        /// <returns>UserList</returns>
        public IQueryable<User> GetUsers()
        {
            return _repository.GetUsers();
        }
        /// <summary>
        /// Returns a specific User by userID
        /// </summary>
        /// <param name="userID">userID</param>
        /// <returns>UsersList</returns>
        public IQueryable<User> GetUsers(int userID)
        {
            return _repository.GetUsers().ByUserID(userID);
        }

        /// <summary>
        /// Saves User
        /// </summary>
        /// <param name="bo"></param>
        public void SaveUser(User uo)
        {
            _repository.SaveUser(uo);
        }
    }
}

 

Svevarn

  • if (NewUser)  
  •     {  
  •         userobj.UserID = uo.UserID;  
  •         _db.Users.InsertOnSubmit(uo);                  
  •     }  
  •   
  •     _db.SubmitChanges();  
  • U r assigning the UserId before User is saved. At this time UserId is zero.

    put this statement userobj.UserID = uo.UserID;   after _db.SubmitChanges(). and i believe it will work fine.

    Leave a Reply