How do I set up my Routing for my MVC Page? - c#

Greetings New to MVC ...
I am creating my first MVC Application, and I have created it as follows:
CustomUtilities/Controllers/GCItemRetrievalController.cs
CustomUtilities/Views/GCItemRetrieval/GCRetrieve.cshtml
CustomUtilities/Views/Web.config
I want to pull up "GCRetrieve.cshtml in my browser ... but I keep getting a 404 Error
http://mainsite/CustomUtilities/GCItemRetrieval/GCRetrieve
what am I doing wrong? I created the folders for the controllers, models, and Views in a seperate folder on the main system.

Your controller should look something like this:
public class GCItemRetrievalController : Controller
{
public ActionResult GCRetrieve()
{
return View();
}
}
When you navigate to the following url:
http://mainsite/CustomUtilities/GCItemRetrieval/GCRetrieve
It should find the controller's GCRetrieve method and execute it. The return View() call will look for a .cshtml file named GCRetrieve.cshtml, as that is the name of the method.

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

When you create a MVC application a class file named as RouteConfig.cs is created in App_Start directory. It has default routing as
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 }
);
}
}
In the above default routing:
if you want call a view CustomUtilities/Views/GCItemRetrieval/GCRetrieve.cshtml
I think CustomUtilities is your project name then use following
http://mainsite/GCItemRetrieval/GCRetrieve
that is
[domanin]/[controllername]/[actionname]
For default routing detail you can refer to http://www.niceonecode.com/Q-A/DotNet/MVC/routing-in-mvc-4/20190

Related

MVC: Using the routing attribute with a url that has an additional segment

I have a controller called Search. A normal url would be the following:
localhost:44351/<ClientName>/Search/ByCity
This would hit my ByCity action within my SearchController.
Now however, a url such as the following example, would also need to hit an action within the SearchController:
localhost:44351/<ClientName>/Search/Pharmacy/ByCity
I need to somehow tell my SearchController, if the url contains "Pharmacy/ByCity", to go to the ByCity action.
I've tried using the routing attribute, but my app still hits my old Pharmacy action instead.
In my RouteConfig, I have this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
Then, in my SearchController, I have this:
public virtual ActionResult Pharmacy()
{
//this is an existing action, which gets hit, even when I type in "Pharmacy/ByCity", which is not what I want to happen.
}
[Route("Pharmacy/ByCity")]
public virtual ActionResult ByCity()
{
//this never gets hit
}
Any idea how to have a url containing "Pharmacy/ByCity" to hit my "ByCity" action, rather than "Pharmacy"?
Thanks
It is possible to achieve with the conventional route by set up like below:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Pharmacy",
url: "{clientname}/{controller}/Pharmacy/{action}",
defaults: new { controller = "search" }
);
routes.MapRoute(
name: "Search",
url: "{clientname}/{controller}/{action}",
defaults: new { controller = "search", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Routes are accessed depending on their Order in the routing table.
For conventional routing (RouteConfig.cs), you could add your specific route before the default route.
Remove your Route[] attributes in the controller
Use the code below for RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// add your specific route, before the default route
routes.MapRoute(
name: "SearchByCity", // random name
url: "Search/Pharmacy/ByCity",
defaults: new { controller = "Search", action = "ByCity" }
);
// this is the default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
If you want to use Attribute Route, follow steps below.
Remove the default route in RouteConfig.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
Then use the controller below, we used RoutePrefix for the controller, and Route for the actions.
[RoutePrefix("Search")]
public class SearchController : Controller
{
[Route("Pharmacy")]
public virtual ActionResult Pharmacy()
{
return View("index");
}
[Route("Pharmacy/ByCity")]
public virtual ActionResult ByCity()
{
return View("index");
}
}

ASP.NET MVC routing add special convention mysitye/string

I am new to ASP.NET MVC. I have a web page with default routing:
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 }
);
}
I have been working on developing an URL shortener that creates 5 character strings in base 32 (A-Z 0-9). My idea is to have the default routing in ASP.NET MVC and add a special case for
// this is the random code generated by my application
www.mypage.com/ASD12
How can I add this exception to my routing and always make URLs (mypage.test/code) land on a specific controller action?
public class CodeController : Controller
{
public async Task<ActionResult> Index(string code)
{
//do things here
}
}
Thank you very much
After searching more,
routes.MapRoute(
name: "specialConvention",
url: "{id}",
defaults: new { controller = "code", action = "Index" }
);
That is the code I was looking for.

ASP.NET MVC - How to model bind query string parameters in application start just like action method of controller?

I would like to ask if it's possible to model bind querystring parameter in application start up just like in controller's action method? is there any attribute class I can use to make this happen? example:
public ActionResult myMethod(MyModel modelName){
return View(modelName);
}
in MVC the application start-up defined in RouteConfig :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional }
);
}
if you want to manipulate param use the id property.

how to show the controller and action in browser tab c# mvc while route config is default

In C# MVC, how can I get the default controller and action to be shown on browser. In my route config default controller/action is AddPerson/Index. But while running the program it is not showing AddPerson/Index on the browser.
My RouteConfig.cs is:
namespace AddPerson
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "AddPerson", action = "Index" }
);
}
}
}
My Browser link : http://localhost:53076/
I want : http://localhost:53076/AddPerson/Index
Content coming is same, only address is not coming .
How to solve this?

Make an MVC controller the default in WebAPI project

I have created my first WebAPI project to learn, which had an index.html page in the root of the project. I set that page as Startup. All working fine. But, I want to use an MVC controller to call the View instead.
So I created a new MVC controller in my Controller folder called "DefaultController". In it, there's a method:
public ActionResult Index()
{
return View();
}
I created a View folder, and off that, a Default folder, in which, I created an Index.cshtml file.
When I start the project, it calls my old index.html. So, I changed the startup to be the index.cshtml, which is wrong - know. MVC calls a controller method. So, I'm trying to work out - how do I call the controller method in my DefaultController?
I think I need to change my routes?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
My plan is to use cshtml pages (instead of html pages) to make use of layouts and allow controllers to initiate the views. Each view will the use an api call back to my WebApi controllers to do the data handling.
Does that seem like a good way to handle my WebAPI/KnockoutJs project?
I just need to know how to get the controller to be the default.
When removing the index.html page, I get the error:
HTTP Error 403.14 - Forbidden The Web server is configured to not list
the contents of this directory.
I think you need to add the controller name to the defaults object as in:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
You need to register both WebAPI routes and MVC routes:
All this should be done in Application_Start method in Global.asax.cs file:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
GlobalConfiguration.Configure(WebApiConfig.Register) is used to configure WebApi (and register api related routes)():
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
RouteConfig.RegisterRoutes(RouteTable.Routes); is used to register MVC routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
You also need verify that the DefaultController that you created is MVC controller (inherits from System.Web.Mvc.Controller) and not WebAPI controller
According to my experience, when you want to call the index.cshtml, in the route config you have to define the controller like this in the RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The controller supposed to be "Home", and the Action is "Index". But, this maproute is for default one. How about if you want to add another one?
routes.MapRoute(
"Article",
"articles",
new { controller = "News", action = "ArticleList" }
);
You can write freely as shown above where "Articles" is the name of maproute and the "articles" is the url. And it would become like this (http://www.domain.com/articles) if you compile controller News and Action ArticleList. And "..../articles" is something you replace (No need define controller or action) and you don't need to open www.domain.com/News/ArticleList it's enough to go to url www.domain.com/articles and the maproute would be automaticaly route to controller news and action articlelist.
That's only my point of view about how maproute works.
CMIIW :)

Categories

Resources