Trouble with global.asax routing - asp.net-mvc-3

I have some links in my webapp that looks like this:
localhost:12345/?something=1
localhost:12345/?something=2
localhost:12345/?something=3
localhost:12345/?something=4
each number at the end is an id that i need to pass to my controller to display information related to it.
I know I need to create a new routes.MapRoute in my global.asax page, but I am not really quite sure how to go about it. I tried this:
routes.MapRoute(
"Id", // Route name
"{controller}/{action}/{*Id}", // URL with parameters
new { controller = "Home", action = "Id", Id = "" } // Parameter defaults
);
---EDIT---
I am only successful getting each individual like to display by doing the following:
routes.MapRoute(
"IdRoute", // Route name
"{Id}", // URL with parameters
new { controller = "Home", action = "Index", id = 1 } // Parameter defaults
);
This does work, however, this only works for one id (specifically 1). I am not quite sure how to go about this, but i need i need:
localhost:12345/?something=1
to display the information for id 1,
localhost:12345/?something=2
to display the information for id 2,
localhost:12345/?something=3
to display the information for id 3.
I there are going to be hundreds of ids so hard coding something in would not be a convenient option. I have had no luck so far. Any help would be much appreciated! Thanks!

routes.MapRouteWithName(
"RootName",
"{id}",
new { controller = "Home", action = "Index", id = 1 });
This will produce links like this localhost/1
If you want this kind of links localhost/?id= 1
Then :
routes.MapRouteWithName(
"RootName",
String.Empty,
new { controller = "Home", action = "Index"});
public ActionResult Index(int id)
{
//do something with id, make query to database whatever
// u usually have model class so you would fill model with your data
var model = new YourModel();
//...
return View("Index", model);
}

If you have following Action in, say, HomeController:
public ActionResult SomeAction(int Id)
{
return View()
}
You may use any of following routes:
//* For Id = 3 this will return path "Home/SomeAction/3"
routes.MapRoute(
name: "First",
url: "{controller}/{action}/{Id}",
defaults: new { controller = "Home", action = "SomeAction", Id= UrlParameter.Optional}
);
//* For Id = 3 this will return path "SomeAction/3"
routes.MapRoute(
name: "First",
url: "{action}/{Id}",
defaults: new { controller = "Home", action = "SomeAction", Id= UrlParameter.Optional}
);
//* For Id = 3 this will return path "Home/SomeAction(3)"
routes.MapRoute(
name: "First",
url: "{controller}/{action}({Id})",
defaults: new { controller = "Home", action = "SomeAction", Id= UrlParameter.Optional}
);
//* For Id = 3 this will return path "LadyGaga/SomeAction/3"
routes.MapRoute(
name: "First",
url: "LadyGaga/{action}/{Id}",
defaults: new { controller = "Home", action = "SomeAction", Id= UrlParameter.Optional}
);

Related

MVC3 Route Using Parameter Name in URL

I have these routes:
routes.MapRoute("ListPage", "{controller}/{action}/{pn}/{ps}", new { controller = "home", action = "index", pn = 1, ps = 10 });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "home", action = "index", id = UrlParameter.Optional });
Which allows me to have URLs like:
/foo/bar/1/10
to control lists of foos on a page (page 1, with 10 items a page). Hooray!
However, the following gives a 404:
/foo/bar/1
Using Url.Action("bar", "foo", new { id = 1}) gives the URL
/foo/bar?id=1
Which then matches correctly to the action signature
public ActionResult Bar(int id) { //stuff }
My thinking is that the first route in the table would not match, as both {pn} and {ps} are required.
So it drops to the second route, which should then match the parameter as {id}.
Obviously my thinking is not correct!
Question is: why is the route not matching without the parameter name?
Just try with interchanging routes postition
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "home", action = "index", id = UrlParameter.Optional });
routes.MapRoute("ListPage", "{controller}/{action}/{pn}/{ps}", new { controller = "home", action = "index", pn = 1, ps = 10 });

MVC3 links SEO - how to make calls from one controller to other controller

I have one problem, I am not sure how to explain but I will try.
I followed this: http://www.deliveron.com/blog/post/SEO-Friendly-Routes-with-ASPnet-MVC.aspx
And I was able to achieve what they describe.
But if I have a page where i wish to call action from other controller, it doesn't work.
It doens't show the link in this way: "this-is-my-link" in the URL.
I don't know what do I do wrong?
in Global.asax
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
);
routes.MapRoute(
"Default2",
"{controller}/{action}/{id}/{pageTitle}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
pageTitle = UrlParameter.Optional
}
);
}
Views/Help/FAQ
#Html.ActionLink(FaqStrings.ContactUs, "ContactUs", "Home", new { id = 1, pageTitle = "link text".ToSeoUrl() })
It says that it can't resolve the ContactUs. Instead of the actions from HomeController, it sees the actions of the HelpController.
In HomeController
[AllowAnonymous]
public ActionResult ContactUs()
{
var model = new ViewModelContactUs
{
Resultmessage = string.Empty,
Youremail = string.Empty,
Yourmessage = string.Empty,
Yourname = string.Empty
};
return View(model);
}
[AllowAnonymous]
[HttpPost]
public ActionResult ContactUs(ViewModelContactUs model)
{
Log.DebugFormat("HomeController-ContactUs()");
........
var model2 = new ViewModelContactUs
{
......
};
ModelState.Clear();
return View(model2);
}
Try moving your controller into the RouteValues dictionary part of your #Html.ActionLink
#Html.ActionLink(FaqStrings.ContactUs, "ContactUs", new {controller="Home", id = 1, pageTitle = "link text".ToSeoUrl() })
EDIT
To address the logic, it has to do with the available signatures of the Html.ActionLink method. Here is the MSDN for information but...
The method signature that you were using was Html.ActionLink("Link Text", "Action", "Contoller", RouteValues, HtmlAttributes). Since you were not passing HtmlAttributes, it was matching up wrong and generating the wrong link. By either moving the controller into the RouteValuesDictionary or passing a , null at the end of your call should solve it. But, I personally don't like throwing nulls around unless I need to, so I typically just define the controller in the RouteValuesDictionary.
If you were not passing any RouteValues, then a call to Html.ActionLink("Link Text", Action, Controller) works with no issues.
Hope that clears it up a little! :)
The underlying problem is that:
#Html.ActionLink(FaqStrings.ContactUs,
"ContactUs",
"Home",
new { id = 1, pageTitle = "link text".ToSeoUrl() })
Will produce an Anchor which when clicked will produce an HTTP GET, however you're method is requiring HTTP POST:
[AllowAnonymous]
[HttpPost] // <-----POST
public ActionResult ContactUs(ViewModelContactUs model)

url parameters missing after adding a comment and redirecting back to blog post

I am teaching myself asp .net mvc3 by creating a blog application. However, I have
problems with comment upload. It is a very subtle error in that everything works when a user leaves a comment. However, the url of the post changes.
So, a blog post has a url
http://localhost:49175/Blog/Details/3/Third-post
This is generated by the url route map here:
routes.MapRoute(
"BlogDetail", // Route name
"Blog/Details/{id}/{urlHeader}", // URL with parameters
new { controller = "Blog", action = "Details", id = UrlParameter.Optional, urlHeader = UrlParameter.Optional } // Parameter defaults
);
Now, when a user leaves a comment - he is directed to a comment controller:
[HttpPost]
public ActionResult Create(BlogDetailsViewModels viewModel)
{
if (ModelState.IsValid)
{
try
{
blogrepository.Add(viewModel.Comment);
return RedirectToAction("Details", "Blog", new { id = viewModel.Comment.BlogID });
}
catch (DataException)
{
ModelState.AddModelError("", "Unable to save comment. Try again, and if the problem persits then contact administrator.");
}
}
// If we got this far, something failed, redisplay form
return RedirectToAction("Details", "Blog", new { id = viewModel.Comment.BlogID });
}
}
However, when somebody leaves a comment - he is redirected back to
http://localhost:49175/Blog/Details/3
I know, as of now there is nothing in the RedirectToAction that passes the urlHeader info. However, I have tried a few things like:
return RedirectToAction("Details", "Blog", new { id = viewModel.Comment.BlogID, urlHeader = viewModel.Blog.UrlHeader });
However, it doesn´t seem to work.
This is the blog details controller:
//
// GET: /Blog/Details/5
public ViewResult Details(int id, string urlHeader)
{
var blogs = blogrepository.GetBlog(id);
var recentblogs = blogrepository.FindRecentBlogs(5);
var archivelist = blogrepository.ArchiveList();
BlogDetailsViewModels viewModel = new BlogDetailsViewModels { Blog = blogs, RecentBlogs = recentblogs, ArchiveList = archivelist };
return View(viewModel);
}
I am stuck for days on this.
-- Full route method as requested --
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"BlogDetail", // Route name
"Blog/Details/{id}/{urlHeader}", // URL with parameters
new { controller = "Blog", action = "Details", id = UrlParameter.Optional, urlHeader = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"BlogArchive", // Route name
"Blog/{year}/{month}", // URL with parameters
new { controller = "Blog", action = "Archive" }, // Parameter defaults
new { year = #"\d{4}", month = #"\d{1,2}", } // Parameter constraints
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
If your form does not contains data for viewModel.Blog.UrlHeader, it will be an empty string, even viewModel.Blog may be null.
You can add a parameter to your post action method, like this:
[HttpPost]
public ActionResult Create(BlogDetailsViewModels viewModel, String urlHeader)
And, in your view that renders the form, use this code to generate the form element:
#Html.BeginForm("Create","Blog",new{urlHeader=Model.Blog.UrlHeader})
Alternatively, you can add a hidden input in your form for the urlHeader. In this way, you don't have to do any of previous two updates.
#Html.HiddenFor(m=>m.Blog.UrlHeader)
Either way, make sure your Model.Blog.UrlHeader is not null or an empty string

ASP.NET MVC basic routing with parameters

I have been trying to learn ASP.NET MVC 3 and things are going well apart from the routing aspect, whatever I try I just can't seem to get them quite right.
I have an ActionLink on the main page:
#Html.ActionLink("Contracts", "List", "Contract",
new { User.Identity.Name, page=1 })
Which is meant to access this method in the ContractController:
public ViewResult List(string user, int page = 1)
{
//snip
}
My routes are:
routes.MapRoute(
null,
"Page{page}",
new { Controller = "Contract", action = "List" }
);
routes.MapRoute(
null,
"Page{page}",
new { Controller = "Contract", action = "List", user = "", page = 1 }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The link now will return a 404 error as it can't find the action 'List' in the controller 'Home', which obviously means it didn't use either of the first routes.
Everything worked before I tried to add parameters to the ActionLink, so basically, what am I doing wrong?
Thanks very much.
Alex,
You're doing all the other bits absolutely correctly, however the actionlink has a missing parameter, try this for your actionlink:
#Html.ActionLink("Contracts", "List", "Contract",
new { User.Identity.Name, page = 1 }, null)
Adding the null as the final param (htmlAttributes) is all that's missing for you in this scenario (there are 9 overloads for Html.ActionLink, so it's VERY easy to miss the correct implementation).

.NET MVC 3 trying to get RedirectToAction to follow the format of {controller}/{action}/{id}/{GUID}

I have to be missing something obvious here.
I would like to ensure all RedirectToAction follow the format of {controller}/{action}/{id}/{GUID} (e.g. http://www.mysite.com/report/edit/23/0975a566-983a-4414-962c-0ab1a921e89d
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
);
routes.MapRoute(
"Custom", // Route name
"{controller}/{action}/{id}/{GUID}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, GUID = UrlParameter.Optional} // Parameter defaults
);
}
I am using the following in the controller:
return RedirectToAction("edit", "report", new { id = id, GUID = getGUIDFromId(id) });
However, I just get the following result:
http://www.mysite.com/report/edit/23?0975a566-983a-4414-962c-0ab1a921e89d
I have had a good search on this but I've found nothing about this particular issue (probably because it is obvious).
Many thanks in advance
Just reverse the order of your route definitions:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Custom",
"{controller}/{action}/{id}/{GUID}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, GUID = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Remember that the order in which you define your routes is important as they are evaluated in this same order by the routing engine. So you should always place specific routes before more general ones.

Resources