参数字典包含参数' userId'的空条目。非可空类型&Systems.Int32

时间:2018-01-08 07:16:13

标签: c#

enter image description here

enter image description here

这是我遇到的错误,这是令人困惑的,因为它只是前一段时间。我不小心点击了一些按钮,这发生了。我正在创建一个"删除"我正在做的一个简单系统的功能......

输出另一个错误说:

  

"参数字典包含参数的空条目   '用户id'非可空类型&Systems.Int32'

这是我的代码:

UserController.cs

public ActionResult DeleteUser(int id)
        {
            UserBusinessLayer userService = new UserBusinessLayer("sqlconn");

            UserModel userModel = new UserModel();

            try
            {
                UserEntity userEntity = userService.GetUserId(id);


                userModel.usr_Id = userEntity.usr_Id;
                userModel.email = userEntity.email;
                userModel.username = userEntity.username;
                userModel.password = userEntity.password;


            }
            catch (Exception ex)
            {

                throw ex;
            }

            return View(userModel);
        }

        [HttpPost, ActionName("DeleteUser")]
        public ActionResult DeleteUserConfirmed(int id)
        {
            UserBusinessLayer userService = new UserBusinessLayer("sqlconn");

            userService.DeleteUser(new UserEntity(){

                usr_Id = id
            });

            return RedirectToAction("List");
        }

UserBusinessLayer.cs

 public UserEntity DeleteUser(int userId)
        {

            UsersDataAccess userService = new UsersDataAccess(_key);

            try
            {
                return userService.DeleteUser(userId);
            }
            catch (Exception exx)
            {

                throw exx;
            }

        }

UserDataAccess.cs

public UserEntity DeleteUser(int userId) {

            SqlConnection oCon = null;
            SqlCommand oCmd = null;
            UserEntity user = null;

            try
            {
                oCon = _connection.openConn();
                string sqlDelete = string.Format("DELETE FROM Users WHERE usr_id = @userId");

                oCmd = new SqlCommand(sqlDelete, oCon);
                oCmd.Parameters.Add(new SqlParameter("@userId", user.usr_Id));
                oCmd.ExecuteNonQuery();

            }
            catch (Exception ex)
            {

                throw ex;
            }

            return user;
        }

2 个答案:

答案 0 :(得分:-1)

我通过添加try catch块来修复。感谢你的帮助。

enter image description here

答案 1 :(得分:-1)

问题在于action参数的名称。

您的控制器将DeleteUserConfirmend操作公开为

public ActionResult DeleteUser(int id)

但由于错误是关于userId没有被填充,这可能意味着路由参数之间的不匹配(我猜这个动作的路由有一个名为userId的参数)和名称方法的参数。

尝试在方法中将id重命名为userId,如下所示:

public ActionResult DeleteUser(int userId)