简体   繁体   中英

ASP.NET MVC pass parameter to stored procedure from controller without Entity Framework

ASP.NET MVC newbie here from a Webforms background. I'm trying to pass the logged in username value via HttpContext.User.Identity.Name to a stored procedure. I'm basically trying to check if the Username exists in the database table or not. I think I'm overlooking something as I'm not quite sure how to pass the User.Identity.Name value to the stored procedure so that it executes and returns a value that either exists or null/blank . Here's my code:

Data access layer class:

    public LoggedUser GetLoggedUser(LoggedUser obj)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["HWebb"].ConnectionString);
        string UserName = "";

        try
        {
            SqlParameter[] parameters ={
                     new SqlParameter("@USER_CRED",obj.User_Name),
                                       };
            SqlCommand cmd = CreateCommand("PortalWeb.GetSelect_User", parameters, con);

            DataTable dt = new DataTable();

            con.Open();
            SqlDataAdapter ada = new SqlDataAdapter(cmd);
            ada.Fill(dt);

            foreach (DataRow dr in dt.Rows)
            {
                if (dr["USER_CRED"] != DBNull.Value)
                    UserName = Convert.ToString(dr["USER_CRED"]);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }

        return obj;
    }

Model:

public class LoggedUser
{
    public string User_Name { get; set; }
}

Controller:

public ActionResult UserVerification()
{
        DataAccess dac = new DataAccess();
        LoggedUser objUser = new LoggedUser();
        objUser = dac.GetLoggedUser(objUser);

        if (HttpContext.User.Identity.Name != objUser.User_Name)
        {
            return RedirectToAction("Index", "Home");
        }
        return null;
}

This won't cause any errors, but I don't think the parameters are being passed correctly as the table returns a null value and I'm not sure if the HttpContext.User.Identity.Name value is even being passed in the first place.

Is there a way to pass the value from the controller to the stored procedure? I'm new to this so I'm sure there I'm missing some code to have this fully functional. I hope someone can help.

Thanks!

I changed the code to this and it works now, although I'm sure there's a better approach to it.

  public string GetLoggedUser(string User_Name)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["HWebb"].ConnectionString);
    string UserName = "";

    try
    {
        SqlParameter[] parameters ={
                 new SqlParameter("@USER_CRED", User_Name),
                                   };
        SqlCommand cmd = CreateCommand("PortalWeb.GetSelect_User", parameters, con);

        DataTable dt = new DataTable();

        con.Open();
        SqlDataAdapter ada = new SqlDataAdapter(cmd);
        ada.Fill(dt);

        foreach (DataRow dr in dt.Rows)
        {
            if (dr["USER_CRED"] != DBNull.Value)
                UserName = Convert.ToString(dr["USER_CRED"]);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
    }

    return UserName;
}

Then in the Controller:

   public ActionResult UserVerification()
    {

        DataAccess dac = new DataAccess();
        string UserNameApp = HttpContext.User.Identity.Name;
        string UserName = dac.GetLoggedUser(UserNameApp);

if (HttpContext.User.Identity.Name != UserName) { return redirecToAction("Index", "Home"); }

    }

Yes, example in traditional way using Ado.net

  1. Create table:
CREATE TABLE [dbo].[Employee](

    [Empid] [int] NOT NULL,
    
    [Name] [varchar](50) NULL,
    
    [City] [varchar](max) NULL,
    [Address] [varchar](max) NULL,CONSTRAINT [PK_Employee] PRIMARYKEYCLUSTERED ([Empid] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY])
  1. Copy script and run in sql server

Now create stored procedure exactly it should match parameter in procedure and propertied from model from .net mvc

Create procedure [dbo].[AddNewEmpDetails] (  
   @Empid int,
   @Name varchar (50),  
   @City varchar (max),  
   @Address varchar (max) 
) as begin  
   Insert into Employee(Empid,Name,City,Address) values(@Empid,@Name,@City,@Address)  
End 
  1. Write sql connection
public bool Insert<T>(string query,T obj) {
    string connection = System.Configuration.ConfigurationManager.ConnectionStrings["Your_connection_name_from_web.config"].ConnectionString;
    SqlConnection con = new SqlConnection(connection);
    SqlCommand com = new SqlCommand(query, con);
    com.CommandType = CommandType.StoredProcedure;
    foreach (PropertyInfo pi in obj.GetType().GetProperties()) {
        com.Parameters.AddWithValue("@" + pi.Name, pi.GetValue(obj, null)?.ToString());
    }
    con.Open();
    int i = com.ExecuteNonQuery();
    con.Close();
    if (i >= 1) {
        return true;
    } else {
        return false;
    }
}
  1. Write model
public class EmpModel {
    [Display(Name = "Id")]
    public int Empid { get; set; }
    
    [Required(ErrorMessage = "First name is required.")]
    public string Name { get; set; }
    
    [Required(ErrorMessage = "City is required.")]
    public string City { get; set; }
    
    [Required(ErrorMessage = "Address is required.")]
    public string Address { get; set; }
    
}

Note:validation is optional i used both BAL and DAL layer for one model.

  1. Create action method
[HttpPost]
public ActionResult AddEmployees(EmpModel Emp) {
     var status = AddEmployee("AddNewEmpDetails",Emp);
     return View();
}

Summary: we should pass data to EmpModel.

now go and check in table data is inserted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM