MVC 4 Error 404 on Created View - c#

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();
}

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);
}

Return to page after save

I want to return to the same page in the page list after save. But now after save it will return to page 1 and not return to page 2, or 3..etc - where the item is that I selected.
I try it like this:
if (SaveDbChanges())
{
// Record an audit trail event for an updated product.
{
ATEvent atEvent = AuditTrailHelper.NewEvent(ATEventType.ProductUpdated, HttpContext, db.Schema, entry.Product);
atEvent.StringArg = entry.Product.Name;
ATEventLogger.Current.LogEvent(atEvent);
}
AddDelayedNotification(Resources.Entity.Environment.ItemSavedMessage, Notification.NotificationType.Success);
return RedirectToAction("Index", new { id = entry.Product.Id });
}
So it has to go back to the Index view but then page number 2 in this case. But it goes back to Index view but then on page 1.
Thank you
I try it like this:
Index view:
<i class="fa fa-fw fa-edit"></i> #Resources.Action.Navigation.Edit
and index method(post):
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Edit(EditProductModel entry, int page)
{
entry.Product.ModificationDate = DateTime.UtcNow;
if (ModelState.IsValid)
{
db.Entry(entry.Product).State = EntityState.Modified;
db.Entry(entry.Product).Property(model => model.Guid).IsModified = false;
db.Entry(entry.Product).Property(model => model.CreationDate).IsModified = false;
db.Entry(entry.Product).Property(model => model.IsProduction).IsModified = false;
entry.Product.IsProduction = StateHelper.IsTestMode() ? false : true;
HandleProductSelections(entry.Product);
SerializeAuthenticationSettings(entry);
SerializePaymentSettings(entry);
SerializeConnectors(entry);
SerializePrefillMappings(entry);
if (SaveDbChanges()) {
// Record an audit trail event for an updated product.
{
ATEvent atEvent = AuditTrailHelper.NewEvent(ATEventType.ProductUpdated, HttpContext, db.Schema, entry.Product);
atEvent.StringArg = entry.Product.Name;
ATEventLogger.Current.LogEvent(atEvent);
}
AddDelayedNotification(Resources.Entity.Environment.ItemSavedMessage, Notification.NotificationType.Success);
//return RedirectToAction("Index", new { id = entry.Product.Id });
//return RedirectToAction("Index", HttpContext.Request.UrlReferrer.AbsoluteUri);
//return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
//return Redirect(Request.UrlReferrer.ToString());
return RedirectToAction("Index", new { page = page });
}
}
AddDelayedNotification(Resources.Entity.Environment.ItemNotSavedError, Notification.NotificationType.Error);
return Edit(entry.Product.Id,2,2);
}
and get:
public ActionResult Edit(int? id, int ID, int page)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
throw new HttpException((int) HttpStatusCode.NotFound, null);
}
SetCreateEditProductLists(product, customerSchema);
EditProductModel editModel = new EditProductModel();
editModel.Product = product;
editModel.Db = db;
//editModel.AuthenticationProviders = AuthenticationProviders.GetProviders(customerSchema);
//editModel.PaymentProviders = PaymentProviders.GetProviders(customerSchema);
//editModel.ConnectorProviders = ConnectorProviders.GetProviders(customerSchema);
DeserializeAuthenticationSettings(editModel);
DeserializePaymentSettings(editModel);
DeserializeConnectors(editModel);
DeserializePrefillMappings(editModel);
ViewBag.Model = editModel;
ViewBag.CurrentPage = page;
return View(editModel);
}
But if I do this:
<i class="fa fa-fw fa-plus"></i> #Resources.Entity.Product.EditProduct
I get this message:
The parameters dictionary contains a null entry for parameter 'page' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(System.Nullable`1[System.Int32], Int32, Int32)' in ''. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
My edit looks now like this:
[HttpGet]
public ActionResult Edit(int? id, int page)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
throw new HttpException((int) HttpStatusCode.NotFound, null);
}
SetCreateEditProductLists(product, customerSchema);
EditProductModel editModel = new EditProductModel();
editModel.Product = product;
editModel.Db = db;
//editModel.AuthenticationProviders = AuthenticationProviders.GetProviders(customerSchema);
//editModel.PaymentProviders = PaymentProviders.GetProviders(customerSchema);
//editModel.ConnectorProviders = ConnectorProviders.GetProviders(customerSchema);
DeserializeAuthenticationSettings(editModel);
DeserializePaymentSettings(editModel);
DeserializeConnectors(editModel);
DeserializePrefillMappings(editModel);
ViewBag.Model = editModel;
ViewBag.CurrentPage = page;
return View(editModel);
}
and my post like this:
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Edit(EditProductModel entry, int page)
{
entry.Product.ModificationDate = DateTime.UtcNow;
if (ModelState.IsValid)
{
db.Entry(entry.Product).State = EntityState.Modified;
db.Entry(entry.Product).Property(model => model.Guid).IsModified = false;
db.Entry(entry.Product).Property(model => model.CreationDate).IsModified = false;
db.Entry(entry.Product).Property(model => model.IsProduction).IsModified = false;
entry.Product.IsProduction = StateHelper.IsTestMode() ? false : true;
HandleProductSelections(entry.Product);
SerializeAuthenticationSettings(entry);
SerializePaymentSettings(entry);
SerializeConnectors(entry);
SerializePrefillMappings(entry);
if (SaveDbChanges()) {
// Record an audit trail event for an updated product.
{
ATEvent atEvent = AuditTrailHelper.NewEvent(ATEventType.ProductUpdated, HttpContext, db.Schema, entry.Product);
atEvent.StringArg = entry.Product.Name;
ATEventLogger.Current.LogEvent(atEvent);
}
AddDelayedNotification(Resources.Entity.Environment.ItemSavedMessage, Notification.NotificationType.Success);
return RedirectToAction("Index", new { page = page });
}
}
AddDelayedNotification(Resources.Entity.Environment.ItemNotSavedError, Notification.NotificationType.Error);
return Edit(entry.Product.Id,92);
}
and my Edit view like this:
#using (Html.BeginForm(new { page = ViewBag.CurrentPage })) {
#Html.AntiForgeryToken()
Oke, I solved, like this:
public ActionResult Edit(int? id, int? page)
both in get and post method. but page is always null
The problem is if I do this:
[HttpGet]
public ActionResult Edit(int? id, int? page)
{
ViewBag.CurrentPage = 2;
it will always return to the second page
Why it works if I do it hardcode, like this: ViewBag.CurrentPage = 2;
but if I do this: ViewBag.CurrentPage = page; then every time page is null
Thank you
The most efficient way of getting back to page 2 (or 3,4,5) would be to add a hidden variable to your edit page with the page number in it. You will have to keep passing the page number to every page after the index page and use it when you need it.
Another thing that you could do, which will put a lot of strain on your database would be to retrieve a list of all the items, then count where your productID is in the list and then calculate which page it should be on, then go to that page:
var ProductIds = db.Products.Select(x=>x.ProductId).ToArray();
int MyProductIndex = ProductIds.IndexOf(id);
int itemsperpage = 30;//or whatever the number of items per page
var pagenum = Math.Ceiling(myproductIndex/itemsperpage);
I solved like this:
in the Index I added:
var id = Session["id"];
Session["id"] = id;

ViewBag and Formatting

Currently I'm using a standard Manage page which looks like:
public ActionResult Manage(string type = "")
{
ViewBag.Type = type;
switch (type)
{
case "EmailAddress":
ViewBag.EmailAddress = lol.UserProfiles.Find((int)Membership.GetUser().ProviderUserKey).EmailAddress;
break;
case "Password":
break;
default:
break;
}
//ViewBag.ReturnUrl = Url.Action("Manage/" + type);
return View();
}
Now my Manage Model page looks like:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(ManageViewModel model)
{
if (ModelState.IsValid)
{
if (model.EmailAddressModel != null)
{
try
{
int userID = (int)Membership.GetUser().ProviderUserKey;
var User = lol.UserProfiles.First(f => f.UserId == userID);
User.EmailAddress = model.EmailAddressModel.EmailAddress;
int saveStatus = lol.SaveChanges();
if (saveStatus == 1)
{
ViewBag.StatusMessage = MessagesEnum.ChangeEmailSuccess;
return RedirectToAction("Manage/EmailAddress", "Account");
}
else
{
ModelState.AddModelError("", MessagesEnum.ChangeEmailFailed);
}
}
catch { }
}
else
{
// ChangePassword will throw an exception rather than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.PasswordModel.OldPassword, model.PasswordModel.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
ViewBag.StatusMessage = MessagesEnum.ChangePasswordSuccess;
return RedirectToAction("Manage/Password", "Account");
}
else
{
ModelState.AddModelError("", MessagesEnum.ChangePasswordFailed);
}
}
}
else
{
}
return View(model);
}
My ManageViewModel class:
public class ManageViewModel
{
public LocalPasswordModel PasswordModel { get; set; }
public LocalEmailAddressModel EmailAddressModel { get; set; }
}
What I was trying to do is make it where if they access multiple pages on Manage such as /Manage/Password and /Manage/EmailAddress and according to those links, it will post a different page. Now first of all, is this the proper way of doing it / is it fine? Second, if it is, I was trying to pass a Sucess message after they change their email to the /Manage/EmailAddress page, but the ViewBag.StatusMessage is not outputting anything on my HTML page. Why is that?
I did a little more research and here are my findings (tell me if it's correct or not). So I should edit the route settings and so something like:
routes.MapRoute(
name: "Manage",
url: "Account/{controller}/{action}/{id}",
defaults: new { controller = "Manage", action = "Index", id = UrlParameter.Optional}
);
And just make a new controller called Manage and create new Functions inside the controller for different pages like ChangeEmail and ChangePassword?
ViewBag and ViewData are only valid for the current request, they wont survive if you do a redirect RedirectToAction. Use TempData instead.
Check the following: ViewBag, ViewData and TempData
If you want your URLs to be /Manage/Password and /Manage/EmailAddress, you dont need to add a new MapRoute, the default one will work. Just use ManageController for you controller class name and "Password" and "EmailAddress" for your function names:
class ManageController
{
public ActionResult Password(...)
{

Categories

Resources