URL Routing Not Working in ASP .Net MVC2 - c#

I am working ASP.Net MVC2 application.
In that i have used URL Routing
To get URL as
https://localhost/StudentDetail/SortField
I have written below code in Global.asax
routes.MapRoute(
"StudentDetail", // Route name
"StudentDetail/{SortField}", // URL with parameters
new { controller = "UDashboard", action = "UAboutMeStudentDetails",
SortField = "Major" }
);
And In my view link is as below
<a href="/StudentDetail?SortField='Major'" >Students</a>
But it is not working. and my URL is
https://localhost/StudentDetail?SortField='Major'
Can anyone please help me to get the required URL..?
I want URL as
https://localhost/StudentDetail/SortField
Thanks In Advance, Prashant

I think you have an incorrect thought on how routing works. Your route:
routes.MapRoute(
"StudentDetail", // Route name
"StudentDetail/{SortField}", // URL with parameters
new { controller = "UDashboard", action = "UAboutMeStudentDetails",
SortField = "Major" }
);
Will take the SortFeild parameter (Major, Gpa, etc), and replace {SortField} with that value. So, using the following actionlink:
#Html.ActionLink("Student Details", "UAboutMeStudentDetails", new {controller="UDashboard", SortField = "Major})
would produce the following HTML
Student Details
Note that the value of SortField has replaced the {SortField} parameter in your route. You would never get a URL looking like what you are requesting as how would you get the value of SortField to the action?

Related

How to I get a FriendlyURL in Razor?

Anyone know how I can turn the URL from:
www.contoso.com/locations?Country=Vietnam
into
www.contoso.com/Vietnam
in Razor, C#, Webforms. (I'm using Webmatrix)
ie - to create FriendlyURLS from search results.
thanks
In RouteConfig.cs, add the following route:
routes.MapRoute(
"Vietnam",
"{vietnam}",
new { controller = "NameOfYourController", action = "NameOfYourAction" },
new { vietnam = UrlParameter.Optional }
);
You have to specify the name of the controller (without the word controller) and the action which will process the request.

C# MVC url parameter not being read

Very new to ASP.net MVC and C# in general. Experience with PHP/NodeJS mostly, a little Java.
I have a method in a controller like so:
public ActionResult ImageProcess(string fileName){
string url = "http://myurl.com/images/" + fileName + ".jpg";
//Code to stream the file
}
And when I navigate to it as "http://myurl.com/Home/ImageProcess/12345" I get thrown a 404 error by the process as it's trying to fetch the file.
If I hard-code it like so...
public ActionResult ImageProcess(string fileName){
string url = "http://myurl.com/images/12345.jpg";
//Code to stream the file
}
...It works just fine, returns my processed image as expected.
Why is this happening?
If you're using the default routes provided for ASP.NET MVC, the fix is simple: change fileName to id.
Example:
public ActionResult ImageProcess(string id) {
string url = "http://myurl.com/images/" + id + ".jpg";
}
In the file RouteConfig.cs you should see something like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "YourProject.Controllers" }
);
This is the configuration that tells the framework how to interpret URL strings and map them to method calls. The parameters for these method calls need to be named the same as in the route.
If you want the parameter to be named fileName, just rename {id} to {fileName} in RouteConfig.cs, or create a new route with a new name and defaults above the default route. But, if that's all you're doing, you might as well stick with the default route and name the parameter id in your action.
Your other option would be to use a query parameter, which would not require any route or variable changes:
link text
Look here for a nice tutorial on routing.
Either change the routing value as #johnnyRose already suggested or change the url to a get parameter, that will let the model binding find the fileName attribute. Like this:
http://myurl.com/Home/ImageProcess?fileName=12345

Asp.net get submit method not working when url is mapped

I have a asp.net mvc form and i want to submit it to same page via get method, it's used for search purpose.
The url is mapped with route key value id.
#using (#Html.BeginForm("Contact", "Home",FormMethod.Get))
{
#Html.TextBox("id", null,
new
{
type = "time"
}
);
<input type="submit" />
}
When the form is generated the action attribute is containing the key value like /Home/Contact/myname.
Here myname is value of id present in url.
When form is submitted value key value for id is getting appended to URL like
http://localhost:57247/Home/Contact/myname?id=11%3A11
The action method is reading myname value instead of 11%3A11.
Action Method:
public ActionResult Contact(string id)
{
ViewBag.Message = id;
return View();
}
It's working fine with post method.
How to fix this?
replace #Html.BeginForm("Contact", "Home",FormMethod.Get)
with #Html.BeginForm()
By default forms are sent to same url they are rendered on and default method is get.
#Html.BeginForm() by default produces a METHOD="POST"
As for your parameter you might want to name it differently.
Default Mvc route is configured like this
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Depending on mvc version it can be in global.asax or App_Start\routeconfig.cs
So your "MyName" in url perfectly matches default id parameter and it has higher priority than query string parameters.
If you name your parameter differently (not id).
Change it to "q" for example in action and in view.
Your URLs will change to /Home/Contact?q=myname and everything should start working as expected.
Now you say that you want a solution with url mapping.
So you have to figure out for yourself what url scheme you want.
If you have a form and want it to post to /home/contact/myname?id=notyourname, than you have a conflict which to solve you will have to somehow change binding priorities in mvc.
Now you can inspect querystring on your own in your action and figure out new id passed without binding. After that you can return RedirectToAction("Contact", new{id = figuredId}) and the url in browser will be what you want it to be.
You can change the query parameter name and have your action recieve 2 parameters
public ActionResult Contact(string id, string q){
if (!string.IsNullOrWhitespace(q)){
return RedirectToAction("Contact",new{id=q});
}
}
To send request to /Home/Contact you should use #Html.BeginForm("Contact","Home",new{id=null}, FormMethod.Get)

ASP.NET MVC2 Custom routing with wildcard or free text url

I have a requirement to add specific functionality to an asp.net mvc2 web site to provide addtional SEO capability, as follows:
The incoming URL is plain text, perhaps a containing a sentence as follows
"http://somesite.com/welcome-to-our-web-site" or
"http://somesite.com/cool things/check-out-this-awesome-video"
In the MVC pipeline, I would like to take this URL, strip off the website name, look up the remaining portion in a database table and call an appropriate controller/view based on the content of the data in the table. All controllers will simply take a single parameter bieng the unique id from the lookup table. A different controller may be used depnding on different urls, but this must be derieved from the database.
If the url cannot be resolved a 404 error needs to be provided, if the url is found but obsolete then a 302 redirect needs to be provided.
Where the url is resolved it must be retained in the browser address bar.
I have had a look at the routing model, and custom routing and can't quite work out how to do it using these, as the controller would not be predefined, based on a simple route. I am also unsure of what to do to provide 404, 302 back to the headers also. Perhpas I need a custom httpmodule or similar but going there went beyond my understanding.
This must be possible somehow... we did it years ago in Classic ASP. Can anyone help with some details on how to achieve this?
Well, the simplest way would be to have an id somewhere in the url (usually the first option)
routes.MapRoute(
"SEORoute", // Route name
"{id}/{*seostuff}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, seostuff = UrlParameter.Optional } // Parameter defaults
);
In your controller you'd have something like
public class HomeController {
public ActionResult Index(int id) {
//check database for id
if(id_exists) {
return new RedirectResult("whereever you want to redirect", true);
} else {
return new HttpNotFoundResult();
}
}
}
If you don't want to use the id method you could do something else like...
routes.MapRoute(
"SEORoute", // Route name
"{category}/{page_name}", // URL with parameters
new { controller = "Home", action = "Index", category = UrlParameter.Optional, pagename = UrlParameter.Optional } // Parameter defaults
);
public ActionResult Index(string category, string page_name) {
//same as before but instead of looking for id look for pagename
}
The problem with the latter is that you would need to account for all types of routes and it can get really difficult if you have a lot of parameters that match various types.
This should get you in the right direction. If you neeed some clarification let me know and I'll see if I can write a specific route to help you
Additional
You could probably do what you're looking for like
public ActionResult Index() {
//Create and instance of the new controlle ryou want to handle this request
SomeController controller = new SomeController();
controller.ControllerContext = this.ControllerContext;
return controller.YourControllerAction();
}
but I don't know any of the side effects by doing that...so it's probably not a good idea - but it seems to work.

ASP.NET MVC multiple url's pointing to the same action

How do i map multiple url's to the same action in asp.net mvc
I have:
string url1 = "Help/Me";
string url2 = "Help/Me/Now";
string url3 = "Help/Polemus";
string url1 = "Help/Polemus/Tomorow";
In my global.asax.cs file i want to map all those url to the following action:
public class PageController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
}
Now in MVC 5 this can be achieved by using Route Attribute.
[Route("Help/Me")]
[Route("Help/Me/Now")]
[Route("Help/Polemus")]
[Route("Help/Polemus/Tomorow")]
public ActionResult Index()
{
return View();
}
Add the following line to your routing table:
routes.MapRoute("RouteName", "Help/{Thing}/{OtherThing}", new { controller = "Page" });
EDIT:
foreach(string url in urls)
routes.MapRoute("RouteName-" + url, url, new { controller = "Page", action = "Index" });
In my case I was looking to simply combine two 'hardcoded' routes into one and stumbled upon this post. I wanted to clean out my RouteConfig.cs a little - because it had so many similar routes.
I ended up using some simple 'or' logic in a regular expression and basically changed:
routes.MapRoute(
"UniqueHomePage",
"Default",
new { controller = "Redirector", action = "RedirectToRoot" }
);
routes.MapRoute(
"UniqueHomePage2",
"Home",
new { controller = "Redirector", action = "RedirectToRoot" }
);
Into a single route:
routes.MapRoute(
"UniqueHomePageGeneric",
"{url}",
new { controller = "Redirector", action = "RedirectToRoot" },
new { url = "Home|Default" }
);
Note for the SEO-savy or -interested: The reason for pointing multiple URL's to one and the same action, is to then redirect them to one and the same page again. In this case the homepage. So the idea is to prevent duplicate content issues. When you use this method for pointing for NON redirecting actions, but actions that show their own views, then you might be CAUSING duplicate content issues :P.
You can just add the routes into your route table as you need them, same as any other route. Just give them unique names, hard coded URL and point them to the same controller / action. It will work fine.
If you use pattern matching instead of hard coded URLs just make sure you get all your routes in the right order so the correct one is selected from the list. So /Help/Me should appear before /Help/{Page} if the hard coded route goes to a different page to the pattern matched one. If you put /help/{page} in the route tabel 1st this will match to /help/me and your hard coded named action for that route would never fire.
On a side note, if this is a public facing site and SEO is important please be careful if you have multiple URLs returning the same data, it will be flagged as duplicate. If this is the case, then use the Canonical tag, this gives all the page rank from all the URLS that go to that single page to the one you name and removes the duplicate content issue for you.

Categories