MVC5 routing Programming C# - asp.net-mvc

public static CustomerInfo Customer
{
get
{
if (System.Web.HttpContext.Current.Session["CustomerData"] == null)
{
System.Web.HttpContext.Current.Response.Redirect("~/Account/Login");
return new CustomerInfo();
}
else
{
return (CustomerInfo)System.Web.HttpContext.Current.Session["CustomerData"];
}
}
set
{
System.Web.HttpContext.Current.Session["CustomerData"] = value;
}
}
Whenever HttpContext.Current.Session["CustomerData"] is null, instead of redirecting to Login view in Account controller it is giving exception.

You can use
Return RedirectToAction("Login", "Account");
to redirect to another controller and method

Try:
if (System.Web.HttpContext.Current.Session["CustomerData"] == null)
{
Session["CustomerLogin"] = "True";
return new CustomerInfo();
}
else
{
Session["CustomerLogin"] = "False";
return (CustomerInfo)System.Web.HttpContext.Current.Session["CustomerData"];
}
Then in your controller check:
if(Convert.ToString(Session["CustomerLogin"]) == "True"){
return RedirectToAction("Login", "Account");
}

Related

The bool value always is always taken as false but its true in database? MVC

I have defined user(admin) type as 'bit' data type in my database. So if value is true it should go to a specific page otherwise it should return the same view. But whenever I pass object (adminObj) with different values the if statement only returns 'false' from database. Can somebody help where is the problem ?
here is my logic
[HttpPost]
public ActionResult Login(tbl_Admin adminObj)
{
studentDBEntities db = new studentDBEntities();
var adminvar = db.tbl_Admin.Where(x => x.Email == adminObj.Email && x.Password == adminObj.Password).FirstOrDefault();
var type=adminObj.Type;
if (adminvar != null)
{
/*var isGlobal=*/
if (adminObj.Type == true)
{
return RedirectToAction("ListAdmin");
}
else
{
return View();
}
}
else
{
return View();
}
}
Values in Database-Table:
When Type=1
Alright, I found the logical error here. I was calling the login object instead of the object which was actually storing the fetched data. So I should call var type=adminvar.Type; instead of var type=adminObj.Type;
So The Corrected logic will be
[HttpPost]
public ActionResult Login(tbl_Admin adminObj)
{
studentDBEntities db = new studentDBEntities();
var adminvar = db.tbl_Admin.Where(x => x.Email == adminObj.Email && x.Password == adminObj.Password).FirstOrDefault();
if (adminvar != null)
{
if (adminvar.Type== true)
{
return RedirectToAction("ListAdmin");
}
else
{
return View();
}
}
else
{
return View();
}
}

How to deal with a non existing session variable?

I am trying to check if a booking record exists, then show its details. Otherwise return to Bookparking page but else part isn't working and shows Object reference not set to an instance of an object because there is no such field with the Session[""]
Controller:
public ActionResult Viewparking()
{
if (IsUserLoggedIn(Session, Request) == false)
{
return RedirectToAction("login");
}
else
{
String id = Session["username"].ToString();
ViewBag.userid = id;
var checkbooking = db.tb_booking.Where(s => s.username == id).FirstOrDefault();
if (checkbooking != null)
{
var show = db.tb_booking.Where(e => e.username == id).FirstOrDefault();
}
else
{ //ViewBag.f = "You have no booking yet!!";
return RedirectToAction("Bookparking", "user");
}
return View();
}
}
As Gabriel noted, you have not null checked the value from the session. Code would be something like this:
public ActionResult Viewparking()
{
if (IsUserLoggedIn(Session, Request) == false)
{
return RedirectToAction("login");
}
else
{
String id = Session["username"]?.ToString();
if (id != null)
{
ViewBag.userid = id;
var checkbooking = db.tb_booking.FirstOrDefault(s => s.username == id);
if (checkbooking != null)
{ // TODO: checkbooking is currently unused, except to check if you can fetch it.
return View();
}
}
// If you reach this code, then either id is null, or the booking was not found
return RedirectToAction("Bookparking", "user");
}
}

How to use Controller.TryUpdateModel outside of the Controller context?

is it possible to use Controller.TryUpdateModeloutside of the Controller context?
For Example suppose that I want to use Controller.TryUpdateModel method in class which does not belong to MyApp.Controllers so how that could be done?.
this is my code.
public ActionResult ValidateAndSignUp(company newCompany)
{
if (ModelState.IsValid)
{
newCompany.CDTO.File = Request.Files["Logo"];
if(new CompanyActions().AddCompany(newCompany))
{
ViewBag.message = newCompany.CDTO.Message;
return View(newCompany.CDTO.RedirectTo);
}
else
{
if (newCompany.CDTO.HasFileError)
{
ModelState.AddModelError("Logo", "Invalid File");
return View(newCompany.CDTO.RedirectTo, newCompany);
}
else
{
ViewBag.error = newCompany.CDTO.Error;
return View(newCompany.CDTO.RedirectTo);
}
}
}
else
{
newCompany.CDTO.Countries = new DropDownLists().GetAllCountries();
return View("signUp", newCompany);
}
}

Refresh a page in MVC

How to refresh the current page in MVC.
[HttpGet]
public ActionResult Request()
{
if (Session["type"] != null && Session["resulttype"] != null)
{
return View();
}
else
{
return null;
}
}
I want to refresh my page in else part. That is when return null value.
You can use Request.UrlReferrer.ToString()
[HttpGet]
public ActionResult Request()
{
if (Session["type"] != null && Session["resulttype"] != null)
return View();
else
return Redirect(Request.UrlReferrer.ToString());
}
You can use the following code in asp.net core
public IActionResult Index(){
return Redirect($"{Request.Path.ToString()}{Request.QueryString.Value.ToString()}");
}
Just Redirect to the Action you want to redirect to. It will refresh your page.
[HttpGet]
public ActionResult Request()
{
if (Session["type"] != null && Session["resulttype"] != null)
{
return View();
}
else
{
return RedirectToAction("Request");
}
}
You can use location.href = location.href; in Javascript code after calling a buttonclick or after a action method call like.
$('#btnme').click(function () {
location.href = location.href;
}

i have been trying to implement custom login where i'll be updating the password but db.savechanges isn't working with my code

public ActionResult ChangePassword(ChangePassword model)
{
if (ModelState.IsValid)
{
UserDetail ud = db.UserDetails.FirstOrDefault(s => s.UserName == User.Identity.Name);
try
{
if (ud.Password == model.OldPassword)
{
ud.Password = model.NewPassword;
TryUpdateModel(ud);
**db.SaveChanges();**
return RedirectToAction("ChangePasswordSuccess");
}
else
{
ViewBag.ErrorMsgForPassword = "old password is not correct";
}
}
catch
{
return View();
}
}
while password change the complex types were not loaded so while updating he password db.savechanges() didn't work so if you load the complex types(addresses in this case) the problem is solved

Resources