0
viewstart嗨我試圖檢索我的會話值並將其用於_layout.cshtml,但每次我得到空異常(Object reference not set to an instance of an object.)
這裏是我的代碼。我究竟做錯了什麼。 layout.cshtml無法加載〜/ Views/Shared/_LayoutHome.cshtml佈局。 beacouse它沒有得到任何會話值。回顧會議varriable並使用它MVS 4(剃刀)
@{
if(HttpContext.Current.Session["LoggedUserType"].ToString() == "superadmin" && HttpContext.Current.Session["DEPTNM"].ToString() == "AlchemyAdmin")
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
else
{
Layout = "~/Views/Shared/_LayoutHome.cshtml";
}
}
這裏是我的控制器代碼,我coudnt用我的會話值。
[HttpPost]
public ActionResult Index(LoginModel model)
{
if (ModelState.IsValid)
{
if (DataAccess.LoginDAL.AdminIsValid(model.LOGINID, model.LOGINPW))
{
var result = (from n in db.AslUsercoDbSet
where n.LOGINID == model.LOGINID &&
n.LOGINPW == model.LOGINPW
select new
{
companyid= n.COMPID,
userid = n.USERID,
deptname= n.DEPTNM,
usertype = n.OPTP
}
);
foreach (var n in result)
{
Session["loggedCompID"] = n.companyid;
Session["loggedUserID"] = n.userid;
Session["LoggedDepartment"] = n.deptname;
Session["LoggedUserType"] = n.usertype;
}
FormsAuthentication.SetAuthCookie(model.LOGINID, true);
return RedirectToAction("Index", "Home");
}
{
ModelState.AddModelError("", "Invalid Username or Password");
}
}
return View();
}
我在這裏添加我的數據訪問層代碼。這驗證了用戶是否存在。
internal static bool AdminIsValid(string username, string password)
{
bool authenticated = false;
string query = string.Format("SELECT * FROM [AslUsercoes] WHERE LOGINID = '{0}' AND LOGINPW = '{1}'", username, password);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
da.Fill(ds);
SqlDataReader sdr = cmd.ExecuteReader();
authenticated = sdr.HasRows;
conn.Close();
return (authenticated);
}
好像沒有錯代碼。你能告訴我們你的控制器代碼嗎? – reptildarat 2014-09-22 05:45:13
__檢查nullablity__。例如'if(HttpContext.Current.Session [「LoggedUserType」]!= null && HttpContext.Current.Session [「DEPTNM」]!= null && HttpContext.Current.Session [「LoggedUserType」]。ToString()==「superadmin 「&& HttpContext.Current.Session [」DEPTNM「]。ToString()==」AlchemyAdmin「)' – Satpal 2014-09-22 05:49:39
我附上我的控制器代碼。請檢查你是否可以幫我做什麼我做錯了 – 2014-09-22 08:51:44