Following all suggested remedies, still my method is not getting called.
The method being called is in the same controller. TEST can be called either by itself through a link on a separate page, or when a user selects a saved "TEST" view that they wish to load again. In this case, the below LoadUserSelectedTransaction is called.
I've tried specifying the controller to use with no luck, hard coding requestType, [HTTPPOST] attribute, removing FormMethod.Post from the view
View is as follows:
using (Html.BeginForm("LoadUserSelectedTransaction", "TransactionList", FormMethod.Post))
Controller is as follows
public class TransactionListController : Controller
{
public static bool userLoaded = false;
public static string userFriendlyName;
public static string transaction;
public static string requestType;
//[HttpPost]
public ActionResult LoadUserSelectedTransaction(FormCollection formdata)
{
userLoaded = true;
userFriendlyName = formdata["UserLoadedTransaction"];
var model = new MyTransactionsDBHandle();
transaction = model.ReturnUserLoadedTransaction(userFriendlyName, User.Identity.Name);
var myTransaction = new MyTransactionsModel();
requestType = myTransaction.ReturnRequestType(transaction);
if (requestType == "")
{
requestType = formdata["CurrentTransactionPage"];
}
// need to check for duplicate transactions types, such as CC_SALE also being a POS Surcharge transaction
// CC_SALE has EMV, ship to, bill to etc, POS Surcharge does not
// CC_VOID with and without card - With card will have NGT_TRACKDATA tag
// DB_SALE with and without cashback - Cashback will have NGT_DC_CASH_BACK_AMOUNT tag
if (requestType == "DB_SALE")
{
if (transaction.Contains("NGT_DC_CASH_BACK_AMOUNT"))
return RedirectToAction("DB_Sale_With_Cash_Back");
return RedirectToAction("DB_Sale_No_Cash_Back");
}
else if (requestType == "CC_SALE")
{
if (transaction.Contains("NGT_EMV_DATA"))
return RedirectToAction(requestType);
return RedirectToAction("CC_POS_Surcharge");
}
else if (requestType == "CC_VOID")
{
if (transaction.Contains("NGT_TRACKDATA"))
return RedirectToAction(requestType);
return RedirectToAction("CC_Void_No_Card");
}
else
return RedirectToAction(requestType);
}
}
Method being called:
public ActionResult TEST(FormCollection formdata)
{
ViewModel model = new ViewModel();
if (userLoaded) // static in same controller
{
userLoaded = false;
if (requestType == "My Transactions")
{
var currentTransactionPage = formdata["CurrentTransactionPage"];
return RedirectToAction(currentTransactionPage);
}
model.myTransactions.ParseUserTransactionString(transaction, model);
}
return View(model);
}
Any suggestions are greatly appreciated, thanks in advance!
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "User", action = "Login", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "ClientTablePages",
url: "{controller}/{action}/{pageNumber}",
defaults: new { controller = "Client", action = "Index", page = UrlParameter.Optional }
);
routes.MapRoute(
name: "DivisionTablePages",
url: "{controller}/{action}/{pageNumber}",
defaults: new { controller = "Division", action = "Index", page = UrlParameter.Optional }
);
routes.MapRoute(
name: "MerchantTablePages",
url: "{controller}/{action}/{pageNumber}",
defaults: new { controller = "Merchant", action = "Index", page = UrlParameter.Optional }
);
routes.MapRoute(
name: "TerminalTablePages",
url: "{controller}/{action}/{pageNumber}",
defaults: new { controller = "Terminal", action = "Index", page = UrlParameter.Optional }
);
routes.MapRoute(
name: "ResetPassword",
url: "{controller}/{action}/{id}",
defaults: new { Controller = "User", action = "UserResetPassword", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "MyTransactions",
url: "{controller}/{action}/{pageNumber}",
defaults: new { Controller = "MyTransactions", action = "MyProfile", page = UrlParameter.Optional }
);
}
}
RedirectToAction returns a 302 redirect to the browser which is always a GET request.
In comparison Server.TransferRequest(url, true) performs a server redirect preserving the postBack values using a POST request.
P.S. Browser won't be aware of this redirect hence the browser url will not reflect the new address
Related
In my ASP MVC application, I need to show the URL path like this:
domain.com/viewName
I have the route config in the follow way:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.RouteExistingFiles = false;
routes.IgnoreRoute("{*allfiles}", new { allfiles = #".*\.(css|js|gif|jpg|png)" });
routes.MapRoute(
"Theme",
"theme/{theme}/{page}",
new { controller = "Theme", action = "Index", page = UrlParameter.Optional },
new[] { "Tenant.Controllers" }
);
routes.MapRoute(
"ThemeSlider",
"theme/slider/{id}",
new { controller = "Theme", action = "Slider" },
new[] { "Tenant.Controllers" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "Tenant.Controllers" }
);
routes.MapRoute(
"Default_tenant",
"{page}",
new { controller = "Home", action = "Index", page = UrlParameter.Optional },
new[] { "Tenant.Controllers" }
);
routes.MapMvcAttributeRoutes();
}
But it does not works, I have to specify the page parameter in the follow way: domain.com/?page=viewName. How should be the route config that leaves the follow routes:
domain.com.co/controller/action/
domain.com.co/view
Any sugestion ?? Thanks in advance
You mean to get rid of the controller? This sort of thing will work, but beware of conflicts between routes in different controllers:
routes.MapRoute(
name: "HomeRoute",
url: "{action}",
defaults: new {controller = "Home", action = "Index"},
constraints: new { homeControllerConstraint = new HomeControllerConstraint() }
);
Now every action in the home controller maps to Domain.com/Action instead of Domain.com/Home/Action.
Here is some reflective code to efficiently work out whether a route is in the home controller, for instance.
internal class HomeControllerConstraint : IRouteConstraint
{
private static readonly Lazy<HashSet<string>> homeMethods = new Lazy<HashSet<string>>(CreateHomeMethods);
private static HashSet<string> CreateHomeMethods()
{
return typeof(HomeController).GetMethods().Select(e => e.Name.ToLower()).ToSet();
}
public static bool Exists(string name)
{
return homeMethods.Value.Contains(name.Trim().ToLower());
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
return homeMethods.Value.Contains(values["action"].ToString().ToLower());
}
}
I am doing a massive overhaul on a custom CMS that I am writing in MVC5. This custom CMS has "pages" that have "urls" stored in a database. For instance if a user requested /stackoverflow in the browser and there was a page in the database with /stackoverflow listed as the url, then I am serving the database content at the specificed CoreCms/Index Controller and view with the database content as a model property. The idea is that I can use this single controller/view to serve up any page in the database.
The rewrite that I am working uses dependency injection and async calls only in the service layer. It seems that I am having a bit of trouble with the RouteConfig RegisterRoutes static method.
Here's some code...
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("FileBrowser/{pathInfo}");
routes.MapRoute(
name: "CmsRoutes",
url: "{*permalink}",
defaults: new { controller = "CmsCorePage", action = "Index" },
constraints: new { url = new CmsCoreRouting() }
);
routes.MapRoute(
name: "ArticlesCategoryRoute",
url: "Articles/{categoryURL}",
defaults: new { controller = "CmsCoreArticles", action = "Index", categoryURL = UrlParameter.Optional }
);
routes.MapRoute(
name: "ArticlesPostsRoute",
url: "Articles/{categoryURL}/{postURL}",
defaults: new { controller = "CmsCoreArticles", action = "ArticlePost", categoryURL = UrlParameter.Optional, postURL = UrlParameter.Optional }
);
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Note that I am rewriting old code and the constraints: new { url = new CmsCoreRouting() } is code that I intend on altering here I believe.
For reference, here is the CmsCoreRouting class...
public class CmsCoreRouting : IRouteConstraint
{
private ICoreCmsServices _coreSvc;
public CmsCoreRouting()
{
}
public CmsCoreRouting(ICoreCmsServices coreSvc)
{
_coreSvc = coreSvc;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (httpContext?.Request?.FilePath == null) { return false; }
string myURL = httpContext.Request.FilePath;
if (myURL.StartsWith("/"))
{
myURL = myURL.Substring(1, myURL.Length - 1);
}
myURL = myURL.ToLower();
var siteId = CoreCms.Core.Settings.CoreCmsSettings.SiteId;
var cmsPage = AsyncUtility.RunSync(() => _coreSvc.PageService.FindBySiteAndUrlAsync(siteId, myURL));
if (cmsPage != null)
{
return true;
}
var cmsArticle = AsyncUtility.RunSync(() => _coreSvc.ArticleService.FindCategoryBySiteAndUrlAsync(siteId, myURL));
if (cmsArticle != null)
{
return true;
}
return false;
}
}
Problem: When MVC starts, it calls the parameterless constructor on CmsCoreRouting (because I told it to in url = new CmsCoreRouting()) but I am not sure how to both use AutoFac's DI so that I don't have to pass around my own instances of the service and repository and DbContext on this RegisterRoutes function.
Any help on this would be great. I would like to do this "right".
Just ask the resolver (AutoFac) to create it for you:
routes.MapRoute(
name: "CmsRoutes",
url: "{*permalink}",
defaults: new { controller = "CmsCorePage", action = "Index" },
constraints: new { url = DependencyResolver.Current.GetService<CmsCoreRouting>() }
);
I have page, which content and URL changes from database. However, I want to set URL like
localhost:xxxx/MyPage
Now I got
localhost:xxxx/Pages/MyPage
which I don't need. What can I do for change it?
My route
routes.MapRoute(
name: "LandingPage",
url: "Pages/{*urltitle}",
defaults: new { controller = "Admin", action = "LandPage", urltitle = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
My code for change content and URL
public ActionResult LandPage()
{
string temp = RouteData.Values["urltitle"].ToString();
var item = RepositoryManager.Instanse.LandingContentRepository.GetItemByURL(temp);
IEnumerable<LandingContent> list = new List<LandingContent>() { item };
ViewBag.HtmlStr = item.HTMLText;
return View(ViewBag);
}
Well, I kinda solved it
my final route
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "LandPage",
url: "{segment}",
defaults: new { controller = "Home", action = "LandingPage" }
And in HomeController you do this
[AllowAnonymous]
public ActionResult LandingPage(string segment)
{some logic}
I want to have my URL to be /{page number} for my home page for example localhost:50915/1 for page 1 for a list of records, my URL routing is as follows:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "EditForm",
url: "{controller}/{formid}",
defaults: new { controller = "ManageForm", action = "Update", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Home",
url: "{page}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
The second MapRoute method is the one which I added to perform the desirable action. It works perfectly fine, but whenever I try to access another Controller "ManageController" for e.g localhost:50915/ManageForm it returns me the home page (same page showing the list of records).
Here is a snapshot of my solution:
Whenever I tried to remove the lines of codes which perform this URL rerouting for the Home Page pagination, everything works fine, but of course the URL will be as localhost:50915?page=1
My HomeController is as follows:
public class HomeController : Controller
{
//
// GET: /Home/
[HttpGet]
public ViewResult Index(int page = 1)
{
const int pageSize = 4;
FormCollection forms = FormService.GetAllActiveForms(page, pageSize);
var formModel = new FormListViewModel
{
Forms = forms,
PagingInfo = new PageInfo
{
PageNumber = page,
PageSize = pageSize,
TotalItems = forms.Count > 0 ? forms[0].TotalRecord : 0
}
};
return View(formModel);
}
}
Help much appreciated thanks.
You cannot use localhost:50915/ManageForm cause it conflicts with another route definition. MVC does not see the difference between "{controller}/{formid}" and "{page}" when your route parameter is optional.
You have to use your first route as localhost:50915/ManageForm/{formId} to get it working.
Solution would be to map a new routing for the manage form to result in the url /ManageForm/Create
I have changed the RouteConfig.cs as follows:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//<host>/{page}
routes.MapRoute(
name: "Home",
url: "{page}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//ManageForm/Create
routes.MapRoute(
name: "CreateForm",
url: "{controller}/Create",
defaults: new { controller = "ManageForm", action = "Index", id = UrlParameter.Optional }
);
//ManageForm/{formid}
routes.MapRoute(
name: "EditForm",
url: "{controller}/{formid}",
defaults: new { controller = "ManageForm", action = "Update", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
My url: http:///Home/addorders //Working Fine
Need to hit like this: http:///addorders
I have added my customized route in RouteConfig: But it does not works for me
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"addorders", // Route name
"addorders/{id}/{str}", // URL with parameters
new { controller = "Home", action = "addorders", id = UrlParameter.Optional, str = UrlParameter.Optional },// Parameter defaults
new[] { "AngularJsExample.Controllers" }
);
}
}
MVC5 provides new feature called Attribute Routing. Instead of registering your routes in Routing Config, You can directly specify routing controller level or action level.
For example
RouteConfig.cs
using System.Web.Routing;
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();// New feature
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Home Controller code
[RoutePrefix("Test")]
[Route("{action=Index}")]// Default Route
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Route("HelloAbout")] //Test/Users/About
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
[Route("~/NewTest/Contact")] //To override the Route "Test" with "NewTest".... NewTest/Contact
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//[Route("home/{id?}")]
public ActionResult Emp(int id)
{
return View();
}
}
This code will change the controller and action name and also change the routing.
Add the new, more specific route before the default in the file (which determines the order it is added to the route dictionary). This is because routes are evaluated for a match to an incoming URL in order. The default MVC route is pretty general, and if route order is not carefully considered when adding additional routes to your project, the default route may inadvertently match a URL intended for a different handler.
Modified code:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"addorders", // Route name
"addorders/{id}/{str}", // URL with parameters
new { controller = "Home", action = "addorders", id = UrlParameter.Optional, str = UrlParameter.Optional },// Parameter defaults
new[] { "AngularJsExample.Controllers" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}