ASP.NET MVC 3 RC Html.Actionlink not generating link - asp.net

As the title says...
I have a route (the first one listed) which looks like this:
routes.MapRoute(
"TopicRoute", // Route name
"forums/{forumSlug}/{topicSlug}", // URL with parameters
new { controller = "Forums", action = "Topic"} // Parameter defaults
);
I can browse to:
/forums/my-forum/my-topic
and the page loads fine. Yet I have a Html.ActionLink that looks like:
#Html.ActionLink(item.Title, "Topic", new { forumSlug ="my-forum", topicSlug = "my-topic" })
And it won't generate the correct link syntax for me? It generates:
My Topic

Don't forget the controller:
#Html.ActionLink(item.Title, "Topic",
new { forumSlug ="my-forum", topicSlug = "my-topic", controller = "Forums" })
or use a named route link:
#Html.RouteLink(item.Title, "TopicRoute",
new { forumSlug = "my-forum", topicSlug = "my-topic" })

Related

asp.net mvc outbound routing from a GET form post

I have a route that looks like this:
new { controller = "ControllerName", action = "PhotoGallery", slug = "photo-gallery", filtertype = UrlParameter.Optional, filtervalue = UrlParameter.Optional, sku = UrlParameter.Optional}
and I have a form that looks like this:
<%using(Html.BeginForm("PhotoGallery", "ControllerName", FormMethod.Get)) {%>
<%:Html.Hidden("filtertype", "1")%>
<%:Html.DropDownList("filtervalue", ViewData["Designers"] as SelectList, "Photos by designer", new { onchange = "selectJump(this)" })%>
<%}%>
Right now when the form is submitted I get the form values appended to the url as query strings (?filtertype=1 etc) Is there a way to get this form to use routing to render the URL?
So the form would post a URL that looked like this:
www.site.com/photo-gallery/1/selectedvalue
and not like"
www.site.com/photo-gallery?filtertype=1&filtervalue=selectedvalue
Thanks!
If you only have some of the parameters present, Mvc will create a Query String type Url unless it finds an exact matching url.
Suggest you will need something like:
routes.Add("testRoute",
new Route("/{action}/{controller}/{slug}/{filtertype}/{filtervalue}",
new { controller = "ControllerName", action = "PhotoGallery", slug = "photo-gallery", filtertype = UrlParameter.Optional, filtervalue = UrlParameter.Optional}
);
make sure this is before your existing route

ASP.Net MVC 2 Area, SubArea and Routes

I have been looking around for a solution for my problem. Found alot of similar issues, but none of them led to a solution for me.
I am trying to register an Area within an Area. This works however it "partially" screws up my routing.
My route registrations in the order they are registered, consider the FooBar and Foo registrations to be coming from AreaRegistrations
routes.MapRoute("FooBar_default",
"Foo/Bar/{controller}/{action}",
new { area = "Foo/Bar", controller = "Home", action = "Index"},
new[] { BarHomeControllerType.Namespace }
);
routes.MapRoute("Foo_default",
"Foo/{controller}/{action}/{id}",
new { area = "Foo", controller = "Start", action = "Index", id = UrlParameter.Optional },
new { controller = new NotSubArea()},
new[] { typeof(StartController).Namespace }
);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("PagesRoute", "Pages/{action}", new { controller = "Pages", Action "Index" }).DataTokens["UseNamespaceFallback"] = false;
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { typeof(HomeController).Namespace }
).DataTokens["UseNamespaceFallback"] = false;
Now the following problem occurs. When going to Website/Foo/ or Website/Foo/Bar links in those pages are generated correctly using:
!{Html.ActionLink<HomeController>(c => c.Index(),"Home", new { area = "Foo/Bar"})}
or
!{ Url.Action("Index", "Home", new { area = "Foo/Bar"}) } //or a different area
However when i use this in my main pages, in other words Website/ or Website/Home etc..
!{Html.ActionLink<HomeController>(c => c.Index(),"Home", new { area = ""})}
or
!{ Url.Action("Index", "Home", new { area = ""}) }
//or with no area identifier specified
It generates the Url: Website/Foo/Bar/Home etc... Which ofcourse is wrong.
When i remove the Area registration for Foo/Bar it all works again. Going to the urls Website/Home/About or Website/Home directly does display the right pages, so im guessing somehow the internal UrlHelper is picking the wrong routes to render.
I tried switching the order of the FooBar_default and Foo_Default routes, so that the Foo_default route is registered before the FooBar_default route, but then the area does not work anymore (resource not found) and the links are still generated incorrectly.
What i find most odd is that removing the Foo/Bar registration solves the problem. I was hoping someone could shed some insight on this matter..
What you need to understand that an Area is just a routing concept which Microsoft have neatly wrapped up the concept or UrlRouting to get people started.
You can actually get the MVC framework to route your request however you like according to your requirements.
What you might need to look at doing, is writing your own RouteHandler. This will enable you to correctly direct how the MVC framework routes any request accoring to your requirements.
See this answer to asp.net mvc complex routing for tree path as an example to get you started.
chris166 outlines that my implementing your own IRouteHandler, and mapping your route to use that instead should get you what you need. Its a bit more effort than using out the box solution of areas, but should get you better results.
routes.MapRoute(
"Tree",
"Tree/{*path}",
new { controller = "Tree", action = "Index" })
.RouteHandler = new TreeRouteHandler();

Default value for parameter in Controller Method is overriding everything

Hello i have just started learning mvc2 and im having a problem with the default value for the parameter page(you can see the method below).
Its always 0 regardless of what i type in the URL. For example this
h.ttp://localhost:52634/Products/List/2
should show page 2 but when in debug mode the page parameter is 0, so im always getting the first page of the list in my view.
i am using the predefined standard routes in global asax when you start a new mvc2 project.
am i missing something?
//This is the ProductsController
public ViewResult List(int page = 0)
{
var products = productsRepo.Products()
//send in source, current page and page size
productList = new PagedList<Product>(products, page, 10);
return View(productList);
}
It's a routing issue, the default route specifies an id property, you're using a property called page. I'm new to MVC myself, but add this route before the default route:
routes.MapRoute("MyRoute", "{controller}/{action}/{page}",
new { controller = "Foo", action = "List", page = UrlParameter.Optional });
Remove the " = 0", and do:
public ViewResult List(int? page)
{
int val = page.GetValueOrDefault(0);
And use val everywhere instead of page. That should work. If not, it's an issue with routing.
HTH.
I know it's very late to answer. As default route for MVC is following
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
which is expecting that parameter name should be id. Now you have 2 options here either change your parameter name to id or the other option is define your own route in route.config file which is under App_Start folder.

ASP.NET - ActionResult parameter is coming back null always when passing string - why?

I am barely starting out with my first project on the ASP.NET MVC project type and I am creating a Details page where instead of passing the templated (int id), I would like to pass a string instead. But when I am in debug mode, and enter this in the URL, "myString" is null. Why so? Do I have to change anything else somehwere else?
So if I go to the URL and enter this:
http://localhost:2345/Bank/EmployeeDetails/3d34xyz
public ActionResult EmployeeDetails(string myString) // myString is null
{
return View();
}
In you Global.asax.cs file, you will have the following route mapped by default:
routes.mapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
That means that an url like http://localhost:2345/Bank/EmployeeDetails/3d34xyz will go to the Bank controller, the EmployeeDetails action and pass the value 3d34xyz into a parameter named id. It is perfectly alright to pass a string, but in order to make it work you have two options:
1) Rename the variable to id in your action method.
public ActionResult EmployeeDetails(string id) { ... }
2) Add another route that matches whatever name you want for your string. Make sure to make it more specific than the default route, and to place it before the default route in the Global.asax.cs file.
routes.mapRoute(
"BankEmployeeDetails"
"Bank/EmployeeDetails/{myString}"
new { controller = "Bank", action = "EmployeeDetails", myString = UrlParameter.Optional });
This will pass a default value of null to myString if no value is passed in the url, but with the url you specified you will pass the value 3d34xyz.
Rename myString to id if you are using the default route table.
Assuming you haven't modified the default routes (In your Global.asax.cs):
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
The method is expecting it to be named "id".
Change the name of myString to id.
I had the same problem, you just need to provide the id in the page where you the hyperlink for Details(in the Bank page here)
#Html.ActionLink("Details", "Details", new { id=""})
This solved my problem hope it helps you.
This for MVC 5.
And when you have tryed all of them and still it comes back null then give a full restart for Visual Studio. That's what eventually helped for me.

How to hide controller name in Url?

How to hide controller name in Url?
I use the ASP.NET MVC.
The original url is: http://www.sample.com/Users.mvc/UserDetail/9615
The "Users" is controller name, the "UserDetail" is action name, and the "9615" is UserId.
How can I hide the controller name and action name in the url.
Just like this: http://www.sample.com/9615
I have writed the following code in the Global.ascx.cs to hide the action name:
routes.MapRoute(
"UserDetail", // Route name
"Users.mvc/{UserId}", // URL with parameters
new { controller = "Users", action = "UserDetail", UserId = "" } // Parameter defaults
);
Using the above code I hid the action name and got this url: http://www.sample.com/Users.mvc/9615
But how can I hide the controller name and get this url: http://www.sample.com/9615
Thanks.
The idea is the same. You do just the thing you did to the action. However, your problem arises from the fact that IIS is probably not mapping www.xyz.com/1234 to ASP.NET runtime. To do so in IIS7, enable integrated mode and in IIS6, add a wildcard mapping in handler map that maps everything to ASP.NET.
To add a wildcard map, see http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx (Search for "IIS6 Extension-less URLs" in that page)
After that, simply add a route:
routes.MapRoute("UserDetails", "{UserID}/{*name}",
new { controller = "Users", action = "UserDetail" , UserID=""});
This should do the trick.
MVC recognizes the difference between "{UserID}" and "{id}" so if you are going to have a route with only "{UserID}" in the Url you need to place it first in the list other wise it never gets hit. And make sure the default includes "id" since it will continually loop over "UserDetails" unless the default references id as apposed to UserID. I found this format works for me:
routes.MapRoute("UserDetails",
"{UserID}",
new { controller = "Users", action = "UserDetail", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = "" } // Parameter defaults
);

Resources