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 }
);
}
Related
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.
I am trying to route an old URL that is domain.com/1024 to my home page in mvc.
I keep getting resource not found errors.
Here is my routeConfig
routes.MapRoute(
name: "1024",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Direct", id = UrlParameter.Optional }
);
My Controller
public ActionResult Direct()
{
return RedirectToAction("Index");
}
If you have your route definition before the default, for example:
routes.MapRoute(
name: "1024",
url: "{id}",
defaults: new { controller = "Home", action = "Direct" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
This will route (host):(port)/ to Index and (host):(port)/1024 to Direct where you can RedirectToAction("Index").
For example a HomeController to demonstrate the point (This ONLY redirects 1024 to index):
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult Direct(int? id)
{
if (id.HasValue && id.Value == 1024)
{
return RedirectToAction("Index");
}
else
{
return View();
}
}
}
This would redirect any id to index:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult Direct(int? id)
{
return RedirectToAction("Index");
}
}
i'm getting this error when i'm navigate browser to url:
localhost:10793/RealEstates/10
this my RouteConfig code:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Main", action = "Index" }
);
routes.MapRoute(
name: "RealEstates",
url: "RealEstates/{action}",
defaults: new { controller = "RealEstates", action = "Index" }
);
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id = UrlParameter.Optional }
);
}
}
my error:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
when changed code to:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}",
// defaults: new { controller = "Main", action = "Index" }
//);
//routes.MapRoute(
// name: "RealEstates",
// url: "RealEstates/{action}",
// defaults: new { controller = "RealEstates", action = "Index" }
//);
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id = UrlParameter.Optional }
);
}
}
it's work but when i call on other actions in controller
localhost:10793/RealEstates/CreateAd
this error found
The parameters dictionary contains a null entry for parameter 'id' of
non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult ViewAd(Int32)' in
'Youe3lan.Controllers.RealEstatesController'. An optional parameter
must be a reference type, a nullable type, or be declared as an
optional parameter.
Parameter name: parameters
and this my controller:
namespace MvcAppliction1.Controllers
{
public class RealEstatesController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ViewAd(int id)
{
return View();
}
public ActionResult CreateAd()
{
return View();
}
}
}
You need to change it to:
routes.MapRoute(
name: "RealEstatesViewAd",
url: "RealEstates/{action}/{id}",
defaults: new { controller = "RealEstates", action = "ViewAd", id UrlParameter.Optional }
);}}
Have a look here it might help:
http://msdn.microsoft.com/en-us/library/cc668201(v=vs.100).aspx
UPDATE
Add this to your controller:
public ActionResult ViewAd(Int32 id)
{
return View();
}
You see
localhost:10793/RealEstates/10
is translated to:
localhost:10793/RealEstates/ViewAdd/10
So you need that method in the controller accepting an it parameter.
you've flagged your id in your route as optional:
id = UrlParameter.Optional
but I bet your controller isn't nullable??
public ActionResult ViewAd(Int32 id)
{
}
So you cant post a null into your id even though the route allows it. If you change this to:
public ActionResult ViewAd(Int32? id)
{
}
You won't get the error message:
The parameters dictionary contains a null entry for parameter 'id' of
non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult ViewAd(Int32)' in
'Youe3lan.Controllers.RealEstatesController'. An optional parameter
must be a reference type, a nullable type, or be declared as an
optional parameter. Parameter name: parameters
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();
}
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(); }
}