Routing with Multiple Parameters using ASP.NET MVC
Parameters are directly supported in MVC by simply adding parameters onto your action methods. Given an action like the following:
public ActionResult GetImages(string artistName, string apiKey)
MVC will auto-populate the parameters when given a URL like:
/Artist/GetImages/?artistName=cher&apiKey=XXX
One additional special case is parameters named "id". Any parameter named ID can be put into the path rather than the querystring, so something like:
public ActionResult GetImages(string id, string apiKey)
would be populated correctly with a URL like the following:
/Artist/GetImages/cher?apiKey=XXX
In addition, if you have more complicated scenarios, you can customize the routing rules that MVC uses to locate an action. Your global.asax file contains routing rules that can be customized. By default the rule looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
If you wanted to support a url like
/Artist/GetImages/cher/api-key
you could add a route like:
routes.MapRoute(
"ArtistImages", // Route name
"{controller}/{action}/{artistName}/{apikey}", // URL with parameters
new { controller = "Home", action = "Index", artistName = "", apikey = "" } // Parameter defaults
);
and a method like the first example above.
MVC routing with multiple parameter with different parameter name
As I had given same name to all route. and route name must be unique, now i have rename the route with different name.
routes.MapRoute(
name: "Admin",
url: "{controller}/{action}/{did}/{docType}",
defaults: new { controller = "Home", action = "Index2", did = UrlParameter.Optional, docType = UrlParameter.Optional }
);
routes.MapRoute(
name: "User",
url: "{controller}/{action}/{uid}/{docId}/{typeId}",
defaults: new { controller = "Home", action = "Index3", uid = UrlParameter.Optional, docId = UrlParameter.Optional, typeId = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
How to route multiple parameters in MVC and C#
You can use attribute based routing where you can pass parameters in the route itself.
like,
//I hope you have already enabled attribute routing and search controller with RoutePrefix as "search"
[Route("{country}")]
public ActionResult Index(string country)
{
//Your business logic
}
[Route("{country}/{searchType}/{location}")]
public ActionResult Index(string country, string searchType, string location)
{
//Your business logic
}
Enabling Attribute based routing : MSND
ASP.NET MVC Routing: Multiple parameter in URL
You can try something like this.
[Route("Book/search/{*criteria}")]
public ActionResult Search(string criteria)
{
var knownCriterias = new Dictionary<string, string>()
{
{"author", ""},
{"title",""},
{"type",""}
};
if (!String.IsNullOrEmpty(criteria))
{
var criteriaArr = criteria.Split('/');
for (var index = 0; index < criteriaArr.Length; index++)
{
var criteriaItem = criteriaArr[index];
if (knownCriterias.ContainsKey(criteriaItem))
{
if (criteriaArr.Length > (index + 1))
knownCriterias[criteriaItem] = criteriaArr[index + 1];
}
}
}
// Use knownCriterias dictionary now.
return Content("Should return the search result here :)");
}
The last parameter prefixed with *
is like a catch-all parameter which will store anything in the url after Book/search.
So when you request yoursite.com/book/search/title/nice/author/jim
, the default model binder will map the value "title/nice/author/jim" to the criteria parameter. You can call the Split
method on that string to get an array of url segments. Then convert the values to a dictionary and use that for your search code.
Basically the above code will read from the spilled array and set the value of knownCriteria
dictionary items based on what you pass in your url.
Routing with multiple parameters in ASP.NET MVC
just add an attribute route
[Route("~/Booking/BookTime/{user?}/{time?}",
public ActionResult BookTime(string user, string Time)
{
return View("BookingPage", bookingSchedule(user));
}
and fix your link
href= ( "Book Time",
"BookTime",
"Booking",
new { user = Model.UserName, time = TimeSlot.ToString() },
null )
Is it possible to have route multiple parameters in asp.net mvc using maproute
Not quite.
You can create a wildcard parameter by mapping {*params}
.
This will give you a single string containing all of the parameters, which you can then .Split('/')
.
MVC Routing with multiple parameters is not working
i came across a solution on
this thing solved my problem
and then rewrote my routes as
routes.MapRoute(
name: "SubCat",
url: "{PCat}/{SCat}/{id}",
defaults: new { Controller = "Adds", Action = "Details" });//, id = UrlParameter.Optional PCat = UrlParameter.Optional, SCat = UrlParameter.Optional,
routes.MapRoute(
name: "ParentCat",
url: "{PCat}/{id}",
defaults: new { Controller = "Adds", Action = "Details" });//,PCat = UrlParameter.Optional,id = UrlParameter.Optional
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
with controller code as
public ActionResult Details(string PCat = null, string SCat = null, int id = 0)
{
Add add = new Add();
if (PCat == null && SCat == null && id > 0 && id != null)
{
add = db.Adds.Single(a => a.AddId == id);
}
if (SCat == null && PCat != null && id > 0 && id != null)
{
add = db.Adds.Single(a => a.AddId == id && a.Category.CategoryName == PCat);
}
if (SCat != null && PCat != null && id > 0 && id != null)
{
add = db.Adds.Single(a => a.AddId == id && a.Category.CategoryName == PCat && a.Category1.CategoryName == SCat);
}
if (add == null)
{
return HttpNotFound();
}
return View(add);
}
instead of
public ActionResult DetailWanted(string PCat=null,string SCat=null, int id=0)
{
if (PCat == "Adds" || PCat == null)
{
return RedirectToAction("Index", "Home");
}
if (id > 0 && id != null)
{
if (SCat != null && PCat != null)
{
//return RedirectToAction("Details", "Adds" , new { @id = id });
return Redirect("/Adds/Details/" + id);
}
else
{
return RedirectToAction("Details", "Adds" , new { @id = id });
}
}
else
{
return RedirectToAction("Index");
}
return RedirectToAction("Index", "Home");}
Multiple Parameters MVC routing
You can achieve that with the following two routes.
// GET library/article/the-templar-order
routes.MapRoute(
name: "Articles",
url: "Library/Article/{id}",
defaults: new { controller = "Library", action = "Article" }
);
// GET library/world/country/city
routes.MapRoute(
name: "Category",
url: "Library/{*categories}",
defaults: new { controller = "Library", action = "Category" }
);
And a slight modification to the target action
public ActionResult Category(string categories) {
categories = categories ?? string.Empty;
var ids = categories.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
//...other code
}
Routing in asp.net mvc with multiple optional parameters
You can try with following example
On RouteConfig :
routes.MapRoute("Name", "tag/{*tags}", new { controller = ..., action = ... });
On Controller :
ActionResult MyAction(string tags) {
foreach(string tag in tags.Split("/")) {
...
}
}
Related Topics
How to Create a Simple Proxy in C#
Why Isn't There Generic Variance for Classes in C# 4.0
Reading 64Bit Registry from a 32Bit Application
Code for Decoding/Encoding a Modified Base64 Url (In ASP.NET Framework)
How to Deserialize a Child Object with Dynamic (Numeric) Key Names
Entity Framework (Ef) Code First Cascade Delete for One-To-Zero-Or-One Relationship
How to Find the Most Recent File in a Directory Using .Net, and Without Looping
Create Instance of Generic Type Whose Constructor Requires a Parameter
Run Single Instance of an Application Using Mutex
Resize Image Proportionally with Maxheight and Maxwidth Constraints
ASP.NET MVC Custom Error Handling Application_Error Global.Asax
Load an Exe File and Run It from Memory
How to Deal with Files with a Name Longer Than 259 Characters
Effective Way to Find Any File's Encoding
Most Common C# Bitwise Operations on Enums