Get a null parameter in action - c#

i have an asp.net mvc4 application in which i have in an action X :
impaire_target = u.Get_Impaire_List().Find(x => x.id_paire == identificateur);
Session["id_paire"] = a;
return RedirectToAction("Page2","Pages",impaire_target );
The action Page2
public ActionResult Page2(Impaire impa)
{
try
{
User u = (User)Session["user"];
if (u.Login == null) RedirectToAction("Index", "Home");
}
catch { return RedirectToAction("Index", "Home"); }
if (impa == null)
{
return View();
}
return View(impa);
}
the problem is that the parameters impa is always null . even i try to replace return RedirectToAction("Page2","Pages",impaire_target ); by return RedirectToAction("Page2","Pages",new{ impa=impaire_target} ); i got the same result.
What is the reasons of this problem?

You can't use ModelBinding with RedirectToAction, so no complex type as anonymous object. Try to convert the object to a RouteValueDictionary:
return RedirectToAction("Page2", "Pages", new RouteValueDictionary(impaire_target));
Side note: you always have to return the RedirectToAction, or it won't work.

You should use Session or TempData for passing complex data between controller actions. Here it is described in details.
Example:
impaire_target = u.Get_Impaire_List().Find(x => x.id_paire == identificateur);
TempData["impa"] = impaire_target;
Session["id_paire"] = a;
return RedirectToAction("Page2","Pages");
The action Page2
public ActionResult Page2()
{
Impaire impa = TempData["impa"] as Impaire;
try
{
User u = (User)Session["user"];
if (u.Login == null) RedirectToAction("Index", "Home");
}
catch { return RedirectToAction("Index", "Home"); }
if (impa == null)
{
return View();
}
return View(impa);
}

Related

How to create the GET and POST methods 'CreateOrEdit()' to be redirected to CreateOrEdit.cshtml both when clicking on Edit and on Create New?

I am trying to customize a POST and GET method called CreateOrEdit(int id, Request request) inside of the controller so that when I am in the Index view which is a list of requests generated from a SQL Table and I click either on the Edit button on the right of each row or on the Create New button, I am redirected to the same View which I have called CreateOrEdit.cshtml. I have managed to make the configuration on RouteConfig.cs but I don't how to come up with an 'if - else' condition in order to check whether id is null or is a number. Someone could help me on solving this?
P. s.: Maybe this is children easy but today is my 9th day as a developer guys :)
I have tried:
1. Add another 2 routes.MapRoute() inside RouteConfig.cs
2. Inside the ActionResult CreateOrEdit() GET and POST methods tried to add a condition in order to know whether id != null but it doesn't seem to help.
[HttpGet]
public ActionResult CreateOrEdit(int? id)
{
return View();
}
[HttpPost]
public ActionResult CreateOrEdit(int? id, Request request)
{
if (/* id is not null (Edit has been clicked) */)
{
try
{
using (DbModels dbModel = new DbModels())
{
dbModel.Requests.Add(request);
dbModel.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
else
{
try
{
// Ketu shtojme logjiken e update-imit
using (DbModels dbModel = new DbModels())
{
dbModel.Entry(request).State = System.Data.EntityState.Modified;
dbModel.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
return View();
}
first your condition is wrong. so just change your condition and then try.
[HttpPost]
public ActionResult CreateOrEdit(int? id, Request request)
{
if (id == null)
{
try
{
using (DbModels dbModel = new DbModels())
{
dbModel.Requests.Add(request);
dbModel.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
else
{
try
{
// Ketu shtojme logjiken e update-imit
using (DbModels dbModel = new DbModels())
{
dbModel.Entry(request).State = System.Data.EntityState.Modified;
dbModel.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
return View();
}**strong text**

How to display user data after he logs in MVC

I need to display the users info when he selects View Profile. How can I do this as im new to mvc. Links to help or an explanation will help a lot. Thanks
Here is my Login Action:
public ActionResult Authorize(The_Pizzatorium.Models.tblUser userModel)
{
using (The_PizzatoriumEntities1 db = new The_PizzatoriumEntities1())
{
var userDetails = db.tblUsers.Where(x => x.dUSerName == userModel.dUSerName && x.dPassword == userModel.dPassword).FirstOrDefault();
if (userDetails == null)
{
userModel.LoginErrorMessage = "Wrong username or password.";
return View("Index", userModel);
}
else
{
Session["UserID"] = userDetails.dID;
Session["userName"] = userDetails.dUSerName;
return RedirectToAction("Index", "Home");
}
}
}
How will I need to make the View Profile Action to display the logged in Users Details?
public ActionResult ViewProfile()
{
return View();
}
when user come to viewprofile action check use session
public ActionResult ViewProfile()
{
if(Session["UserID"]!=null)
{
//check user uid datatype
//then store in variable
int useesionid=COnvert.toint32(Session["UserID"].tosting())
var userDetails = db.tblUsers.Where(x => x.uid==useesionid).ToList();
///here your code
return View( userDetails );
}
Check the below code, to get the user details if logged in other wise redirecting to login page.
public ActionResult ViewProfile()
{
if(Session["UserID"] != null)
{
using (The_PizzatoriumEntities1 db = new The_PizzatoriumEntities1())
{
int userId = Convert.ToInt32(Session["UserID"].ToString());
var userDetails = db.tblUsers.Where(x => x.dID == userId).FirstOrDefault();
if (userDetails != null)
{
return View(userDetails);
}
}
}
return RedirectToAction("Login", "Account"); // Redirect to your login page
}

How can I redict to same page after session expire in MVC project?

//I Have a Action Method
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(VmUser_User VmUser_User)
{
if (VmUser_User.User_User.UserName == null ||
VmUser_User.User_User.Password == null)
{
VmUser_User.LblError = "Please enter Username and Password";
return View(VmUser_User);
}
//Return valid user
if (VmUser_User.LoginUser() > 0)
{
Session["One"] = VmUser_User;
return RedirectToAction("Index", "Home");
}
else
{
VmUser_User.LblError = "User/Password does not match!";
}
return View(VmUser_User);
}
//And another Action Method
public async Task<ActionResult> Common_Unit()
{
Oss.Romo.ViewModels.User.VmUser_User user =
(Oss.Romo.ViewModels.User.VmUser_User)Session["One"];
if (user == null)
{
return RedirectToAction("Login", "Home");
}
vmCommon_Unit = new VmCommon_Unit();
await Task.Run(() => vmCommon_Unit.InitialDataLoad());
return View(vmCommon_Unit);
}
When a valid user login application, it redirect to Home/Index page, then he request for Common/Common_Unit page. After expire the session and user relogin the application I want to redirect in last requested page like Common/Common_Unit, please someone help me to solve this problem.
My Question : When a authorized user browse a specific page then he inactive some time. In the min time session out occurred and user go to login page. After login I want to redirect user on this specific page. Sorry for my Bad English
Try to use ReturnUrl parameter, like this:
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(VmUser_User VmUser_User)
{
if (VmUser_User.User_User.UserName == null ||
VmUser_User.User_User.Password == null)
{
VmUser_User.LblError = "Please enter Username and Password";
return View(VmUser_User);
}
//Return valid user
if (VmUser_User.LoginUser() > 0)
{
Session["One"] = VmUser_User;
if (Request.QueryString["ReturnUrl"] != null & Request.QueryString["ReturnUrl"] != "")
{
Response.Redirect(Request.QueryString["ReturnUrl"]);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
VmUser_User.LblError = "User/Password does not match!";
}
return View(VmUser_User);
}
//And another Action Method
public async Task<ActionResult> Common_Unit()
{
Oss.Romo.ViewModels.User.VmUser_User user =
(Oss.Romo.ViewModels.User.VmUser_User)Session["One"];
if (user == null)
{
return RedirectToAction("Login", "Home", new { ReturnUrl = "/Common/Common_Unit" });
}
vmCommon_Unit = new VmCommon_Unit();
await Task.Run(() => vmCommon_Unit.InitialDataLoad());
return View(vmCommon_Unit);
}

Wrong view being returned for controller method

I have a controller method that is returning the wrong view. The view I have is the same name as the controller method "AssignTask.cshtml". The method is "public virtual ActionResult AssignTask(ManageTaskModel model) "
Can anyone see what I'm doing wrong?
[HttpGet]
public virtual ActionResult ManageTasks()
{
try
{
var model = new ManageTaskModel ();
model.assignedPSUsers = Orchestrator.GetAssignedPSUsers();
return View(model);
}
catch (Exception e)
{
ModelState.AddModelError("ErrorMsg", e.Message);
};
return this.RedirectToAction("Index");
}
[HttpPost]
public virtual ActionResult ManageTasks(ManageTaskModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
try
{ //User has seleced the user that they want to see Tasks for
if (model.selectedUser != null && model.newUser==null)
{
model.assignedPSUsers = Orchestrator.GetAssignedPSUsers();
model.FcvsTaskList = Orchestrator.GetTasksForAssignedPSUser(model.selectedUser);
return AssignTask(model);
}
}
catch (Exception e)
{
ModelState.AddModelError("ErrorMsg", e.Message);
return View(model);
}
return this.RedirectToAction("Index");
}
[HttpGet]
public virtual ActionResult AssignTask(ManageTaskModel model)
{
if (model.selectedUser != null && model.newUser == null)
{
**return View(model);** //returning the ManageTask instead of AssignTask View
}
return this.RedirectToAction("Index");
}
In your ManageTasks action you return AssignTask(model). This doesn't work, because the request context still remembers that the user actually called ManageTasks. That's why it returns the view for ManageTasks.
The right way to do it is like that:
return RedirectToAction("AssignTask", model); // remember to pass the model here
You can see that if you put this line in AssignTask:
HttpContext.Request.Path
If you access it from ManageTasks using return AssignTask(model), the value will be "/YourController/ManageTasks".
If you either call this action directly from browser or with RedirectToAction the value will be "/YourController/AssignTask".
you can't redirect that way. instead of return AssignTask you need
return RedirectToAction("AssignTask");
and pass an id or something there. you will need to recreate the model in your AssignTask method

MVC 4 Error 404 on Created View

I have this controller:
[Authorize]
public class CheckoutController : Controller
{
ShoppingCartContext storeDB = new ShoppingCartContext();
const string PromoCode = "FREE";
[HttpPost]
public ActionResult AddressAndPayment(FormCollection values)
{
var order = new Order();
TryUpdateModel(order);
try
{
if (string.Equals(values["PromoCode"], PromoCode,
StringComparison.OrdinalIgnoreCase) == false)
{
return View(order);
}
else
{
order.Username = User.Identity.Name;
order.OrderDate = DateTime.Now;
//Save Order
storeDB.Orders.Add(order);
storeDB.SaveChanges();
//Process the order
var cart = Models.ShoppingCart.GetCart(this.HttpContext);
cart.CreateOrder(order);
return RedirectToAction("Complete",
new { id = order.OrderId });
}
}
catch
{
//Invalid - redisplay with errors
return View(order);
}
}
public ActionResult Complete(int id)
{
// Validate customer owns this order
bool isValid = storeDB.Orders.Any(
o => o.OrderId == id &&
o.Username == User.Identity.Name);
if (isValid)
{
return View(id);
}
else
{
return View("Error");
}
}
}
And I have created a View called AddressAndPayment under Checkout, so it goes to localhost/Checkout/AddressAndPayment but I only get a 404 error, even if I right click on the View and click on view in Page Inspector. I don't know why its not even showing the view when it is created.
You need a corresponding HttpGet method, as your current one only accepts a HttpPost request. Add the following:
[HttpGet]
public ActionResult AddressAndPayment()
{
return View();
}

Categories

Resources