How to handle ASP MVC Url Parameter containing forward slash - asp.net-mvc-routing

I am working on a ASP.Net MVC project. I have a particular controller action that accepts a date value in the form yyyy/mm/dd. So the URL becomes
http://localhost/MyProject/PublicReview/GetReviews/2012/10/29.
where GetReviews is an action and 2012/10/29 the parameter.
My RouteConfig is as follows:
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 });
}
How should I change the routevalues ? What should be the order of MapRoute values?

I've not tested this, but I'm guessing this will work in your scenario:
routes.MapRoute(
"Reviews", "PublicReview/GetReviews/{year}/{month}/{day}"
{ controller = "PublicReview", action = "GetReviews" };
Note that this will need your GetReviews method to have three properties of "year", "month" and "day". You'll then have to parse them into a DateTime.
Taken from http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-custom-routes-cs which uses "-" for date separators.

Related

Request.QueryString in MVC

In my HomeController I'm trying to get information using Request.QueryString
string aa = Request.QueryString["aa"];
string bb = Request.QueryString["bb"];
So In the address bar I am expecting something like:
< something >?aa=12345&bb=67890
I created a new route:
routes.MapRoute(
"Receive",
"Receive",
new { controller = "Home", action = "Index" }
);
And I'm trying to use it in this way:
http://localhost:54321/Receive?aa=12345&bb=67890
But I'm getting the following error:
The resource cannot be found.
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.
Requested URL: /Receive
I think your routing is goofed which is why you are getting a 404. Please look at some tutorials, specifically here: asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs
Also, like #YuriyFaktorovich says, you really shouldn't be using Request.QueryString, but rather passing those as parameters to your action method
Example in VB:
Function Retrieve(ByVal aa as String, ByVal bb as String) as ActionResult
You can access the Query String values in 2 ways...
grab the values in the controller initialization
use the values in your action
specifying the route with those variables
1 - grab the values in the controller initialization
protected override void Initialize(RequestContext requestContext) {
// you can access and assign here what you need and it will be fired
// for every time he controller is initialized / call
string aa = requestContext.HttpContext.Request.QueryString["aa"],
bb = requestContext.HttpContext.Request.QueryString["bb"];
base.Initialize(requestContext);
}
2 - use the values in your action
public void ActionResult Index(string aa, string bb) {
// use the variables aa and bb,
// they are the routing values for the keys aa and bb
}
3 - specifying the route with those variables
routes.MapRoute(
"Receive",
"Receive/{aa}/{bb}",
new {
controller = "Home",
action = "Index",
aa = UrlParameter.Optional,
bb = UrlParameter.Optional }
);
Use "Receive/" for the url in the route, and don't use Request.Querystring.
You can modify your action to be
public ActionResult Index(string aa, string bb) {...}
The ASP.Net MVC framework will hydrate those items for you.
Your HTTP 404 error is because your new route is very likely in the wrong place. Make sure your new route is before the default route:
routes.MapRoute(
"Receive",
"Receive",
new { controller = "Home", action = "Index" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Return PartialView in MVC3 Area is not searching in area

I am working on an ASP.Net MVC 3 RC project. I have one area named Drivers. I have a LoadPartial() action in a controller in the Drivers area that returns a PartialView(string, object); When this is returned I get an error on my webpage that says "The partial view 'PublicAttendanceCode' was not found." It searched the following locations:
~/Views/AttendanceEvent/PublicAttendanceCode.aspx
~/Views/AttendanceEvent/PublicAttendanceCode.ascx
~/Views/Shared/PublicAttendanceCode.aspx
~/Views/Shared/PublicAttendanceCode.ascx
~/Views/AttendanceEvent/PublicAttendanceCode.cshtml
~/Views/AttendanceEvent/PublicAttendanceCode.vbhtml
~/Views/Shared/PublicAttendanceCode.cshtml
~/Views/Shared/PublicAttendanceCode.vbhtml
Why is it not searching in the Drivers Area?
I have the following pretty basic routes in Global.asax.cs:
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
}
);
}
And in DriversAreaRegistration.cs
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Drivers_default",
"Drivers/{controller}/{action}/{id}",
new { action = "RequestLeave", id = UrlParameter.Optional }
);
}
What am I missing that will make it look in the drivers area for the partial?
How are you providing area name to PartialView() method? I think you should be passing it in new { area = "Drivers" } as routeValues parameter.
The way that the MVC view engines know the area that they should look in is based on the route that was used to process the request.
In the case of the controller action that you have, are you certain that the request was processed by the area's route definition, or is it possible that the request was processed by the more general route that you defined in global.asax?
There are only four overloads of the method PartialView and it seems like neither of them accept routeValues as a parameter.
I solved this problem like this:
return PartialView(
VirtualPathUtility.ToAbsolute("~/Areas/MyArea/Views/Shared/MyView.cshtml"));
It works, but looks ugly.
This works too:
return PartialView("~/Areas/Admin/Views/Shared/MyView.cshtml", model);

MapRoute (Asp.Net MVC 2.0 .NET 4.0)

is there any possibility to create a maproute which would use always one method and it won't be necessary to put it in address?
I mean I've got controller with one method (Index) and it displays items depend on methods argument.
public ActionResult Index(string TabName)
{
var tab = (from t in BlogDB.Tabs
where t.TabName == TabName
select t).SingleOrDefault();
ViewData.Model =(Tab)tab;
return View();
}
and what I want is that I can display items putting address "www.example.com/Tabs/TabName" without "/Index/" between Tabs and TabName. I've tried:
routes.MapRoute(
"Tabs1",
"Tabs/{TabName}",
new { controller = "Tabs", action = "Index", TabName = UrlParameter.Optional }
);
But it doesn't work.
do you still have the default route? and if yes is it defined before this one?
Your problem is that asp.net mvc is trying to find the Tabs controller and the Tabname action.
Put this route before the default {controller}/{action} route

actionlink not resolving urls related to route

I have the following route ( it's the first in my global.asax )
routes.MapRoute(
"AdminCompany", // Route name
"{controller}.aspx/{action}/{companyId}/{id}", // URL with parameters
new { controller = "Home", action = "Index", companyId = "", id = "" } // Parameter defaults
);
if i navigation to
"Order/DisplayAdmin/2/79000180" it resolves correctly
However if i do the following
Html.ActionLink("View", "DisplayAdmin", new {companyId = Model.CompanyId, id = order.OrderNumber }, new { #class = "button add" })
it displays
/Order.aspx/DisplayAdmin/39068760?companyId=0
which also works, but isn't so pretty :)
Here is my Controller Method
public ActionResult DisplayAdmin(int companyId, [DefaultValue(0)]int id, [DefaultValue(0)] int orderItemStatusId)
{
var viewModel = DisplayAdminViewModel(companyId, id, _statusResponses);
return View(viewModel);
}
Am i calling ActionLink the wrong way? how do i get the nice Urls?
only thing I can think of that is happening is that its falling back to the Default route, I did a copy paste of both your route and the html.ActionLink and it works perfectly for me displaying it like "/Order.aspx/DisplayAdmin/39068760/45456", i did replicate the same fault like you get if the naming isn't the same in the route and action link.
Use the overload of ActionLink that has a RouteValueDictionary argument.
It appears that you are currently using the overload with the "object" argument and it's going to a workable, but not as clean, url.

ASP.NET MVC 2.0: How to read querystring value

I am trying to build a small ASP.NET MVC 2 application.I have a controller class with the below method in it
public ActionResult Index()
{
TestMvc.Models.PersonalInformation objPerson = new TestMvc.Models.PersonalInformation();
objPerson.FirstName = "Shyju";
objPerson.LastName = "K";
objPerson.EmailId="shyju#company.com";
return View(objPerson);
}
And when the page (View) being called, i can see this data there as my view has these data's displaying. Now i want to know how can i pass a query string in the url and use that id to build the PersonalInformation object.Hoe can i read the querystring value ? Where to read ?
I want the quesrtstring to be like
http://www.sitename/user/4234 where 4234 is the user id
http://www.sitename/user/4234 is not a querystring. The querystring is the part of the URL that comes after the ?, as in http://www.sitename/user?userId=42
However, the default routes that come with the MVC project template should allow you to simply change the signature of your action method to
public ActionResult Index(int id)
and you should get the desired result. You should look into how routing works in MVC if you want full control of your URLs.
Also, note that the index action is usually used for showing a list of all objects, so you probably want the Details action for showing 1 user object.
What you want is to modify your action to accept an id like so:
public ActionResult Index(string id)
{
TestMvc.Models.PersonalInformation objPerson = new TestMvc.Models.PersonalInformation();
if (!string.isNullOrEmpty(id))
{
objPerson = getPerson(id);
}
return View(objPerson);
}
Then add a route to your global.asax:
routes.MapRoute(
"MyRoute", // Route name
"user/{id}", // URL with parameters
new { controller = "mycontroller", action = "index", id = ""} // Parameter defaults
);