Below is the Controller code:
public class HomeController : Controller
{
//
// GET: /Home/
public string Index(string name)
{
return "Welcome to MVC_Demo"+name;
}
}
and below is the Global.asax.cs codes:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
}
When I run the application and browse for (http://localhost/MVC_Demo/home/index/pradeep) it shows only,
"Welcome to MVC_Demo" as the output, and not as "Welcome to MVC_Demo Pradeep" i.e the parameter name "Pradeep" is not getting displayed.
Considering me just a beginner any help would be highly appreciated.
As your route states, the default parametername is id. So either change the default parametername to be name like this
routes.MapRoute(
"Default",
"{controller}/{action}/{name}",
new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
Or you can change the name of the parameter to be id and match the route.
public string Index(string id)
{
return $"Welcome to MVC_Demo {id}";
}
One more solution is to specify the parametername explicitly as a QueryString parameter:
http://localhost/MVC_Demo/home/index?name=pradeep
Related
UPDATE: It works fine is I add another parameter. I have no idea why.
Not sure what I am doing wrong, this route looks the same as the other routes, I've looked at all the other stackoverflow posts on the subject and everything looks up to snuff. Maybe someone can see something I can't?
Error: action parameter can't be null
The url: http://localhost:1319/EntryHistory/Entry/B2AAAA4A-B174-4C28-924F-A3B2027DD745
EntryHistoryController.cs:
public class EntryHistoryController : Controller
{
public ActionResult Entry(string entryId)
{
Guid parsedEntryId = Guid.Parse(entryId);
var history = new EntryHistoryService().BuildEntryHistoryViewModel(parsedEntryId);
return View(history);
}
}
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
...
EntryHistoryRoutes(routes);
...
}
private static void EntryHistoryRoutes(RouteCollection routes)
{
routes.MapRoute(
"revisionhistory",
"entryhistory/entry/{entryId}",
new
{
controller = "entryhistory",
action = "entry",
entryId = UrlParameter.Optional
}
);
}
add attribute routing
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
...... your routes
//convention-based routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
and action
[Route("~/entryhistory/entry/{entryId}")]
public ActionResult Entry(string entryId)
I'm not sure if this is possible using mvc routing, I haven't been able to find a similar example.
I have about 5~ controller actions that are the same method, so I'd like to refactor them into a single action. I'd like to pass an enum value to the controller to tell it what path it should pass to lower layers.
Example:
public ActionResult ViewPage(int id, PageEnum page) {
var model = MyService.GetModelForTemplate(id, page);
return ("ViewPage", model);
}
Then the user could access this either through /PagesTypeOne/ViewPage/, or /PagesTypeTwo/ViewPage/. Both routes leading to the same endpoint.
Route table attempt:
routes.MapRoute(
name: "typeOne",
url: "PagesTypeOne/{action}/{id}",
defaults: new { controller = "Pages", action = "ViewPage", id = UrlParameter.Optional, page = PageEnum.TypeOne, }
);
routes.MapRoute(
name: "typeTwo",
url: "PagesTypeTwo/{action}/{id}",
defaults: new { controller = "Pages", action = "ViewPage", id = UrlParameter.Optional, page = PageEnum.TypeTwo, }
);
This obviously isn't working.
Is there a way I can do something like this? It would make my code much more concise.
screen != page, so if the property on the anonymous type matches the parameter it will work:
public ActionResult ViewPage(int id, PageEnum screen) {
var model = MyService.GetModelForTemplate(screen);
return ("ViewPage", model);
}
Updated: Created a empty application and it work flawlessly:
namespace MvcApplication6
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Test1",
"PagesTypeOne/{action}/{id}", // URL with parameters
new { controller = "Home",
action = "Index",
id = UrlParameter.Optional,
page = PageEnum.PageOne } // Parameter defaults
);
routes.MapRoute(
"Test2",
"PagesTypeTwo/{action}/{id}", // URL with parameters
new { controller = "Home",
action = "Index",
id = UrlParameter.Optional,
page = PageEnum.PageOne } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home",
action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
public enum PageEnum
{
Undefined,
PageOne,
PageTwo
}
Controller:
namespace MvcApplication6.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ViewPage(int id, PageEnum page)
{
var debug = 1; // break point
return new EmptyResult();
}
}
}
you can make it completely dynamic with one route definition:
// the route must be defined as the first route
routes.MapRoute(
name: "typeTwo",
url: "{page}/ViewPage/{id}",
defaults: new { controller = "Pages", action = "ViewPage", id = UrlParameter.Optional },
new { page= getPageTypes() }
);
the getPageTypes method:
private static string getPageTypes()
{
var pageTypes = Enum.GetNames(typeof(PageEnum));
return string.Join("|", pageTypes );
}
but PagesTypeOne/ViewPage/4 part must match the enum's name.
i have an action which takes two parameters but when action is called, parameters are displayed in the url as query string like this:
localhost:34795/Verification?DepartmentID=3&SubDepartmentID=2
I know that using custom url route i can change this to like this:
localhost:34795/Verification/3/2
but i am unable to do this i added this code to Globas.asax but no outcome till"
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( "Blog", // Route name
"Verification/{DepartmentID}/{SubDepartmentID}", // URL with parameters
new { controller = "Verification", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
//routes.MapRoute(
// "Default", // Route name
// "{controller}/{action}/{id}", // URL with parameters
// new { controller = "TestDetails", action = "GetSubDepartmentID", id = "" } // Parameter defaults
//);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
}
i did this way but nothing happened, what i am doing wrong?
This should do the trick:
routes.MapRoute("Blog",
"Verification/{DepartmentID}/{SubDepartmentID}",
new {
controller = "Verification",
action = "Index",
DepartmentID = UrlParameter.Optional,
SubDepartmentID = UrlParameter.Optional
}
);
Then in your Index function in VerificationController:
public ActionResult Index(int DepartmentID, int SubDepartmentID)
I have got the solution, after thorough debugging i realized that in asp.net mvc 4 it creates some classes by default in application Shared directory and there for registering routes application was calling this method:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
}
You see here its calling RegisterRoutes method which is in RouteConfig.cs file which means in RouteConfig class its not calling the method of Global.asax, this was the issue and i got mad solving it and at last this result i got and got thing to work.
Here is my RouteConfig.cs code which solved the issue and make things work:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("home", "", new { controller = "Home", action = "Index" });
routes.MapRoute(
"Verification", // Route name
"Verification/{DepartmentID}/{SubDepartmentID}", // URL with parameters
new
{
controller = "Verification",
action = "Index",
DepartmentID = UrlParameter.Optional,
SubDepartmentID = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
I'm not sure how I should ask the question, but I am trying to route a SHA1 encryption to be accepted by the ID.
Example
/Home/Index/Id
/Home/Index/A8-75-93-36-DA-4F-74-E1-E0-6B-78-98-DC-AE-FF-1F-17-CA
Is there a better way to do this?
If you have the default route setup:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
and then a controller action taking an id parameter:
public class HomeController: Controller
{
public ActionResult Index(string id)
{
...
}
}
and navigate to /Home/Index/A8-75-93-36-DA-4F-74-E1-E0-6B-78-98-DC-AE-FF-1F-17-CA the Index action of the Home controller will be invoked and the id parameter will be passed the hash value.
I'm learning about creating custom routes in ASP.NET MVC and have hit a brick wall. In my Global.asax.cs file, I've added the following:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
}
The idea is for me to able to navigate to http://localhost:123/home/filter/mynameparam. Here is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Filter(string name)
{
return this.Content(String.Format("You found me {0}", name));
}
}
When I navigate to http://localhost:123/home/filter/mynameparam the contoller method Filter is called, but the parameter name is always null.
Could someone give a pointer as to the correct way for me to build my custom route, so that it passes the name part in the url into the name parameter for Filter().
The Default route should be the last one.
Try it this way:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I believe your routes need to be the other way round?
The routes are processed in order, so if the first (default, OOTB) route matches the URL, that's the one that'll be used.