How to configure a URL with 3 levels in ASP.NET MVC? - asp.net

Using ASP.NET MVC, I need to configure my URLs like this:
www.foo.com/company : render View Company
www.foo.com/company/about : render View Company
www.foo.com/company/about/mission : render View Mission
If "company" is my controller and "about" is my action, what should be "mission"?
For every "folder" (company, about and mission) I have to render a different View.
Anyone knows how can I do that?
Thanks!

First, setup your views:
Views\
Company\
Index.aspx
About.aspx
Mission.aspx
AnotherAction.aspx
In your GlobalAsax.RegisterRoutes(RouteCollection routes) method:
public static void RegisterRoutes(RouteCollection routes)
{
// this will match urls starting with company/about, and then will call the particular
// action (if it exists)
routes.MapRoute("mission", "company/about/{action}",
new { controller = "Company"});
// the default route goes at the end...
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
In the controller:
CompanyController
{
public ViewResult Index() { return View(); }
public ViewResult About() { return View(); }
public ViewResult Mission() { return View(); }
public ViewResult AnotherAction() { return View(); }
}

Related

Route Confusion with Single Action

I am clearly having issue understanding the routes here or trying to achieve which is not possible.
I have this in my RouteConfig:
routes.MapRoute(
name: "Explorer",
url: "{controller}/{action}/{prefix}/{value}",
defaults: new { controller = "Explorer", action = "Index", prefix ="", value = UrlParameter.Optional }
);
And in Explorer Controller I have the following:
[RoutePrefix("Explorer")]
public class ExplorerController : Controller
{
public ActionResult Index()
{
return View();
}
[Route("id/{value}")]
public ActionResult Import(decimal? importId)
{
return View();
}
[Route("text/{value}")]
public ActionResult Import(string importWindow)
{
return View();
}
}
One of the ACTION (Import) has different PREFIX such as window and id but whenever I try to access it (such as https://localhost/Explorer/Import/window/helloWorld OR https://localhost/Explorer/Import/id/200) it keeps giving me the following error
The current request for action 'Import' on controller type
'ExplorerController' is ambiguous between the following action
methods: System.Web.Mvc.ActionResult
Import(System.Nullable`1[System.Decimal]) on type
projectname.Controllers.ExplorerController System.Web.Mvc.ActionResult
Import(System.String) on type projectname.Controllers.ExplorerController
I know it is ambiguous but I have a prefix which should make it non-ambiguous.
What am I doing wrong here and how to achieve this outcome if this is not the right way to do it?
Apply the [Route()] attribute for action methods in the controller class:
[RoutePrefix("Explorer")]
public class ExplorerController : Controller
{
// GET: Explorer
public ActionResult Index()
{
return View();
}
// Example: https://localhost/Explorer/Import/id/200
[Route("Import/id/{importId:decimal}")]
public ActionResult Import(decimal? importId)
{
return View();
}
// Example: https://localhost/Explorer/Import/window/helloWorld
[Route("Import/{text}/{importWindow}")]
public ActionResult Import(string importWindow)
{
return View();
}
}
Define only the Default route in the RegisterRoutes() method:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

Url.Action() does not use good route config

I have overridden a default route in my routes configuration :
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute("MyController_OverriddenAction",
"MyController/OverriddenAction",
new { controller = "MyOverriddenController", action = "OverridenAction" },
new[] { "Plugin" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "home", action = "Index", id = UrlParameter.Optional }
);
}
}
If I call MyController/OverriddenAction, the overridden action OverriddenAction in MyOverriddenController is displayed. It works.
But if I call #Html.Action("OverriddenAction", "MyController"), the default route is called.
Why? What is the solution?
My controllers :
public class MyOverridenController : Controller
{
public ActionResult OverriddenAction()
{
return Content("overridden");
}
}
public class MyController : Controller
{
public ActionResult OverriddenAction()
{
return new EmptyResult();
}
[...]
}
You should use following syntax
#Html.Action("OverriddenAction", "MyOverriden")
while calling the method directly like MyController/OverriddenAction it looks for the entry in MapRoute. However, while using #Html.Action you should use the actual controller name.

MVC parameter-Routing is null

I have the following in my RouteConfig:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{caseID}",
defaults: new { controller = "Generator", action = "Index", caseID = UrlParameter.Optional }
);
}
}
And my ActionResult method:
public ActionResult Index(string caseID) {
//some code
var currentcase = new Something.Read(caseID);
//some other code
return View(model);
}
My url looks like localhost/Generator/Index/dee7aff5-0a34-4965-936f-a08f1dae5c43
Now my caseID should be "dee7aff5-0a34-4965-936f-a08f1dae5c43" but it is null and i can't figure out why.
Can anyone help me?
UPDATE
If the url is
localhost/Generator/Index/?caseID=dee7aff5-0a34-4965-936f-a08f1dae5c43
instead of
localhost/Generator/Index/dee7aff5-0a34-4965-936f-a08f1dae5c43
it runs well.
Replace CaseID with id in your route.config file hopefully it will work.And in your action as well with id

ASP.NET MVC3 Linking Area "Resource cannot be found"

I just barely created a new Area to organize my code.
But currently I am having trouble actually linking it from my "base" or "root" index page, to my new area page.
#Html.ActionLink("Tube Record Form", "BearingAssemblyForm", "_HiCT", new { area = "HICT" }, null)
public class HICTAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "HICT";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"HICT_default",
"HICT/{controller}/{action}/{id}",
new {controller = "_HiCT", action = "BearingAssemblyForm", id = UrlParameter.Optional }
);
}
}
The resource cannot be found.
And it seems its linked wrongly
Requested URL: /HICT/HiCT/BearingAssemblyForm
Controller: HiCT,
View/Action: BearingAssemblyForm, Area: HICT.
How would I like this?
Thank you so much.
Try this:
#Html.ActionLink("LinkText",
"ActionName",
"ControllerName",
new { area = "HICT" }, null)
I think you're not using the correct #Html.ActionLink method overload.
First off all, see if your area is registered correctly:
public class Routes : AreaRegistration
{
public override string AreaName
{
get
{
return "HICT";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"HICT_default",
"HICT/{controller}/{action}/{id}",
new { controller = "_HiCT", action = "BearingAssemblyForm", id = UrlParameter.Optional }
);
}
Make sure you're calling RegisterAllAreas inside the Global.asax.cs file:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
...
}
/Master/BearingAssemblyForm
usually, Master is the controller and the 2nd part is action, so it seems your controller name is different than your route.
Its been a wile but this should work.
#Html.ActionLink("Tube Record Form", "action", "Area/controller")
Are you calling:
AreaRegistration.RegisterAllAreas();
on Application_Start in your Global.asax? What server are you using for development Cassini, IISExpress, IIS?
Edit after reviewing more detailed information.
In your Admin Area Registration File if you have this code
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new string[] { "CoolProject.Web.Areas.Admin.Contollers" }
);
I think there is a typo in CoolProject.Web.Areas.Admin.Contollers and it should be CoolProject.Web.Areas.Admin.Controllers?

asp.net mvc routing id parameter

I am working on a website in asp.net mvc. I have a route
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
// Parameter defaults
);
which is the default route. And I have a method
public ActionResult ErrorPage(int errorno)
{
return View();
}
Now if I want to run this code with http://something/mycontroller/Errorpage/1
it doesn't work. But if I change the parameter name to id from errorno
it works.
Is it compulsory to have same parameter name for this method? Or do I need to create separate routes for such situations?
So, you have a parameter named errorno, and you want it to have a value from parameter id. This is obviously the binding problem.
How to solve it:
create a class for model binder:
public class ParameterBinder : IModelBinder
{
public string ActualParameter { get; private set; }
public ParameterBinder(string actualParameter)
{
this.ActualParameter = actualParameter;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object id = controllerContext.RouteData.Values[this.ActualParameter];
return id;
}
}
create a custom attribute for custom model binding:
[AttributeUsage(AttributeTargets.Parameter)]
public class BindParameterAttribute : CustomModelBinderAttribute
{
public string ActualParameter { get; private set; }
public BindParameterAttribute(string actualParameter)
{
this.ActualParameter = actualParameter;
}
public override IModelBinder GetBinder()
{
return new ParameterBinder(this.ActualParameter);
}
}
apply the new attribute to your action parameters as needed:
public ActionResult ErrorPage(
[BindParameter("id")]
int errorno)
{
return View();
}
Now your errorno will have the value, which was passed as id for your url.
Note: you can remove the paramter id from the example above, if you are sure you need it solved only for id.
Leaving this way will allow you bind other parameters too.
Option 1
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
public ActionResult ErrorPage(int id)
{
return View();
}
Option 2
routes.MapRoute(
"Default",
"{controller}/{action}/{errorno}",
new { controller = "Home", action = "Index", errorno = UrlParameter.Optional }
);
public ActionResult ErrorPage(int errorno)
{
return View();
}
Option 3
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
public ActionResult ErrorPage(int id)
{
int errorno = id;
return View();
}
use the bind attribute prefix:
public ActionResult Customer([Bind(Prefix = "id")]string cname) {}
#Parminder
The default route can handle all action with one parameter "id". And I think not every action need this parameter. So I change my default route
routes.MapRoute(
"Default",
"{controller}/{action}",
new { controller = "Home", action = "Index"}
);
and you can add a new route:
routes.MapRoute("errorpage", "yourcontroller/errorpage/{errorno}",
new {controller="controllername", action="errorpage"});
this just handle your controll name is "controllername". If you want to handle all controller, you can add this:
routes.MapRoute("errorpage", "{controller}/errorpage/{errorno}",
new {controller="controllername", action="errorpage"});
This method will create very much code in global.asax if you need a lot of custom route.
You could either rename the parameter in the default root (which probably is not a good idea) or rename it in the action method. Adding another root will not help because it will be the same as the default one and given an url the routing engine cannot distinguish between the two and will always take the first one in the list.
try to use the same name of parameter in action method as in in the route table url parameter.
global.asx
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
myController
public ActionResult ErrorPage(int id)
{
return View();
}

Resources