为什么我的UserId返回用户名导致转换错误?

时间:2016-11-28 18:53:42

标签: c# asp.net-mvc-4 asp.net-identity asp.net-roles

我遵循本教程http://tutlane.com/tutorial/aspnet-mvc/asp-net-mvc-membership-provider-to-create-users-roles-mapping-roles-to-users

当我尝试添加角色时,出现以下错误:

Input string was not in a correct format.

在这一行

var User = GetUserName_BY_UserID(Convert.ToInt32(objvm.UserId));

我认为问题是UserId返回的是用户名而不是UserId,但我不知道自己在获取用户名时做错了什么。

的AccountController RoleAddToUser

  [HttpGet]
        public ActionResult RoleAddToUser()
        {
            AssignRoleVM objvm = new AssignRoleVM(); //http://tutlane.com/tutorial/aspnet-mvc/asp-net-mvc-membership-provider-to-create-users-roles-mapping-roles-to-users
            objvm.RolesList = GetAll_Roles();
            objvm.Userlist = GetAll_Users();
            return View(objvm);
        }

   [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(AssignRoleVM objvm)
        {
            //Validation inside RoleAddtoUser ActionMethod: First validation to check both dropdownlist are select or not.
            if (objvm.RoleName == "0")
            {
                ModelState.AddModelError("RoleName", "Please select RoleName");
            }
            if (objvm.UserId == "0")
            {
                ModelState.AddModelError("UserName", "Please select Username");
            }
            if (ModelState.IsValid)
            {
                GetUserName_BY_UserID(Convert.ToInt32(objvm.UserId));
                var User = GetUserName_BY_UserID(Convert.ToInt32(objvm.UserId));
                Roles.AddUserToRole(User, objvm.RoleName);
                ViewBag.ResultMessage = "Username added to the role successfully !";

                objvm.RolesList = GetAll_Roles();
                objvm.Userlist = GetAll_Users();
                return View(objvm);
            }
            else
            {
                objvm.RolesList = GetAll_Roles();
                objvm.Userlist = GetAll_Users();
            }
            return View(objvm);
        }

的AccountController GetUserName_BY_UserID

public string GetUserName_BY_UserID(int UserId)
{
    using (UsersContext context = new UsersContext())
    {
        var UserName = (from UP in context.UserProfiles
                        where UP.UserId == UserId
                        select UP.UserName).SingleOrDefault();
        return UserName;
    }
}

模型 AccountModel.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;

namespace AccountModule_Attempt_5.Models
{
    public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }

        public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<webpages_UsersInRoles> webpages_UsersInRole { get; set; }
       // public DbSet<RegisterModel> UserProfiles { get; set; }
        //public DbSet<RegisterModel>Users { get; set; }
       // public DbSet<UsersRole> UsersRoles { get; set; }   
    }

    [Table("webpages_UsersInRoles")]
    public class webpages_UsersInRoles
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }

        public int RoleId { get; set; }
    }

AssignRoleVM.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace AccountModule_Attempt_5.Models
{
    public class AssignRoleVM
    {

        [Required(ErrorMessage = " Select Role Name")]
        public string RoleName { get; set; }
        [Required(ErrorMessage = "Select UserName")]
        public string UserId { get; set; }

        public List<SelectListItem> Userlist { get; set; }
        public List<SelectListItem> RolesList { get; set; }
    }
}

UserProfile.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace AccountModule_Attempt_5.Models
{
    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }

        [Required]
        public string UserName { get; set; }
        public string EmailId { get; set; }

        [Required]       
        public string CustomerId { get; set; }

    }

}

Roles.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AccountModule_Attempt_5.Models
{

    [Table("webpages_Roles")]
    public class Role
    {
        [Required(ErrorMessage = "Enter Role name")]
        //[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        public string RoleName { get; set; }

        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int RoleId { get; set; }
    }
}

2 个答案:

答案 0 :(得分:0)

问题的主要原因是因为您尝试将字符串变量(不是数字)转换为Int32。为了将UserId转换为Int 32,它应该是数字。

此外,userID不应与除numeric之外的其他字符混合使用。

例如,如果userID是“101”,它将被转换没有问题。但是用户ID“Zbra101”无法转换为Int 32。

答案 1 :(得分:0)

您可以尝试这些。 在AccountController中添加更改。

[HttpGet]
 public ActionResult RoleAddToUser()
{
        AssignRoleVM objvm = new AssignRoleVM(); 
        objvm.RolesList = GetAll_Roles();
        objvm.Userlist = GetAll_Users();
        return View(objvm);
}

   [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RoleAddToUser(AssignRoleVM objvm)
    {

        if (objvm.RoleName == "0")
        {
            ModelState.AddModelError("RoleName", "Please select RoleName");
        }
        if (objvm.UserId == "0")
        {
            ModelState.AddModelError("UserName", "Please select Username");
        }
        if (ModelState.IsValid)
        {

            var User = objvm.UserId;
            Roles.AddUserToRole(User, objvm.RoleName);
            ViewBag.ResultMessage = "Username added to the role successfully !";

            objvm.RolesList = GetAll_Roles();
            objvm.Userlist = GetAll_Users();
            return View(objvm);
        }
        else
        {
            objvm.RolesList = GetAll_Roles();
            objvm.Userlist = GetAll_Users();
        }
        return View(objvm);
    }