![](/img/trans.png)
[英]Pass generic list to stored procedure using ASP.NET MVC and Entity Framework
[英]ASP.NET MVC pass parameter to stored procedure from controller without Entity Framework
ASP.NET 來自 Webforms 背景的 MVC 新手。 我正在嘗試通過HttpContext.User.Identity.Name
將登錄的用戶名值傳遞給存儲過程。 我基本上是在嘗試檢查Username
名是否存在於數據庫表中。 我想我忽略了一些東西,因為我不太確定如何將User.Identity.Name
值傳遞給存儲過程,以便它執行並返回一個存在或null/blank
的值。 這是我的代碼:
數據訪問層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;
}
這不會導致任何錯誤,但我認為參數沒有被正確傳遞,因為表返回一個null
值,我不確定HttpContext.User.Identity.Name
值是否在第一個中被傳遞地方。
有沒有辦法將值從 controller 傳遞給存儲過程? 我對此很陌生,所以我確定我缺少一些代碼來使其功能齊全。 我希望有人能幫幫忙。
謝謝!
我將代碼更改為此,現在可以正常工作,但我確信有更好的方法。
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;
}
然后在控制器中:
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"); }
}
是的,例如使用 Ado.net 的傳統方式
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])
現在准確地創建存儲過程,它應該匹配過程中的參數和來自 .net mvc 的 model 的屬性
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
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;
}
}
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; }
}
注意:驗證是可選的我為一個 model 同時使用了 BAL 和 DAL 層。
[HttpPost]
public ActionResult AddEmployees(EmpModel Emp) {
var status = AddEmployee("AddNewEmpDetails",Emp);
return View();
}
總結:我們應該將數據傳遞給 EmpModel。
現在 go 並插入簽入表數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.