Good Day,
This is my first question, so please be kind. I have just made the move from forms to mvc.
I have made the following route (below). I constructed a partial view that also contains 2 other partial views (as seen below).
When submitted the url will be something like 'Find/Index?Region=3&Interest=1'
What is the best way to create a friendly url matching the route defined
'Find/Index/In-Wales-3/Sport-1'? I could post and then redirect, but I thought this maybe inefficient. A better approach maybe to use jquery?
Please also indicate if the design used is correct or if it could be improved upon? The reason for separating the views, is because they are used on multiple views.
Thanks in advance!
Route Config
routes.MapRoute(
name: "Find",
url: "{controller}/{action}/In-{region}-{rid}/{interest}-{iid}",
defaults: new { controller = "Find", action = "Index", region = UrlParameter.Optional,
rid = UrlParameter.Optional,
interest = UrlParameter.Optional,
iid = UrlParameter.Optional
});
Partial View That Is Rendered On Master Page
#model SimpleFriendFinderModel
<h1>Find</h1>
<div>
#using (Html.BeginForm("Index", "Find", FormMethod.Get))
{
#Html.Partial("_RegionDropDown", #Model.Regions)
#Html.Partial("_InterestDropDown", #Model.Interests)
<div>
<button>SEARCH</button>
</div>
}
</div>
Region Partial View
#model IEnumerable<Region>
<select id="Region" name="Region">
<option>REGION</option>
#{ foreach(var item in Model) {
<option value="#item.RegionID">#item.RegionName</option>
}
}
</select>
The other partial view is a replica of Region but obviously a different model.
For the PartialViews; it is the way to go if you re-use it on other pages. You can think of it a bit as 'encapsulated logic'.
UPDATE: Ignore the above if you are just using a partial view for a dropdownlist. There is a HtmlHelper, Html.DropDownListFor() for that.
For the first part; the order is relevant:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Pretty",
url: "{controller}/{action}-{id}/Something",
defaults: new { controller = "Test", action = "Foo", id = UrlParameter.Optional }
);
//default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
for example will work if you would like to format the URL like:
http://local:23802/Test/Foo-5/Something
Related
My goal is have the link appear as mydomain.com/viewPhone/1
Currently, the link is appearing as Home/phoneCatalog , and without displaying my ID
ROUTING
routes.MapRoute(
name: "phoneCatalog",
url: "viewPhone/{phoneID}",
defaults: new { controller = "Home", action = "phoneCatalog",}
);
CONTROLLER
public ActionResult phoneCatalog(int phoneID)
{
//CODE HERE
}
MVC VIEW
<span class="floatL w100">#Html.ActionLink(title, "phoneCatalog", "Home", new { phoneID = orderItem.phoneID }, null)
</span>
Use #Html.RouteLink instead. You probably still have the fall-back {controller}/{action}/{id} route defined.
#Html.RouteLink(title, "phoneCatalog", new { phoneID = orderItem.phoneID })
You should use attribute routing. It gives you more flexibility if you like different names for your actions rather than default values.
It is easy to use.
Check out:
http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
[Route("viewPhone/{phoneID:int}")]
public ActionResult phoneCatalog(int phoneID)
{
//CODE HERE
}
Try this.
I am using .Net Framework 4.5 and MVC4 with Entity Framework.
I currently have the following code in my RouteConfig.cs:
routes.MapRoute(
name: "Jobs",
url: "job_openings.aspx",
defaults: new { controller = "AboutUs", action = "Index", id = UrlParameter.Optional }
);
But we now have a page anchor in the About Us page. When a user types in /job_openings.aspx, I want them to be taken right down to that anchor. Does anyone know how to do that?
I've tried doing a MapPageRoute, but that doesn't seem to work:
routes.MapPageRoute("Jobs", "job_opening.aspx", "~/AboutUs#News");
This is the URL I am trying to get to: ~/AboutUs#News from this one: job_opening.aspx
Is this possible?
Sooo thanks to this amazing post here: ASP.NET MVC Redirect to action with anchor
I was actually able to get this to work...BUT I had to do some...finagling.
In the Route config I added the id of 1 so I could handle it in the controller:
routes.MapRoute(
name: "Jobs",
url: "job_openings.aspx",
defaults: new { controller = "AboutUs", action = "Index", id = 1 }
);
This is what I did in my controller to handle this request (Using what that one page provided):
public ActionResult Index(int id = 0)
{
if (id == 1)
{
return Redirect(Url.RouteUrl(new { controller = "AboutUs", action = "Index" }) + "#News");
}
return View();
}
Now here is the tricky part I had to bang my head on for a while. For some reason on the redirect, it literally went to the route config and took the first item that had controller = "AboutUs", action = "Index" and went to it. So I was in an infinite loop.
So I added this ON TOP of the "Jobs" route:
routes.MapRoute(
name: "AboutUs",
url: "AboutUs",
defaults: new { controller = "AboutUs", action = "Index", id = UrlParameter.Optional }
);
Once I did that, it actually worked!
I recently discovered Areas in ASP.NET MVC 4, which I have successfully implemented, but I'm running into troubles with the #Html.ActionLink helper in my Razor views. The URL this helper generates always seems to be relative to the URL of the current page.
I have my web site configured in IIS 7 (Win7) as an Application virtual directory at /Foo.
I have two Areas registered: Admin and Blogs. I have the default code in the AdminAreaRegistration.cs and BlogsAreaRegistration.cs files. I added namespaces = new[] { "MvcProject.Controllers" } to the defaults of the default RouteConfig:
public class RouteConfig
{
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,
namespaces = new[] { "MvcProject.Controllers" }
}
);
}
}
When I go to the home page for my site: http://localhost/Foo, it correctly loads the "home" page for my site. At this point, all the action links have their correct URLs.
Sample code from MvcProject/Views/Shared/_Layout.cshtml
<h2>Main Navigation</h2>
<ul>
<li>#Html.ActionLink("Home", "Index", "Home")</li>
<li>#Html.ActionLink("Blogs", "Index", "Blogs/Home")</li>
<li>#Html.ActionLink("Admin", "Index", "Admin/Home")</li>
</ul>
This is correctly rendering the HTML as:
<h2>Main Navigation</h2>
<ul>
<li>Home</li>
<li><a href="/Foo/Blogs/Home"></li>
<li><a href="/Foo/Admin/Home"></li>
</ul>
When I navigate in the browser to "Blogs" for instance, this URL correctly loads in the browser: /Foo/Blogs/Home.
Now the links in my main navigation change their URLs to:
<h2>Main Navigation</h2>
<ul>
<li>Home</li>
<li><a href="/Foo/Blogs/Blogs/Home"></li>
<li><a href="/Foo/Blogs/Admin/Home"></li>
</ul>
Notice that "Blogs/" is appended to the IIS virtual directory name, so that /Foo/Blogs/Home is now /Foo/Blogs/Blogs/Home.
The controllers and views are rendering fine, it's just the calls to #Html.ActionLink in my MvcProject/Views/Shared/_Layout.cshtml view are not working as I expected.
It feels like I'm missing something trivial, but no amount of searching has come up with an answer. Every blog post and tutorial I've found for implementing Areas in ASP.NET MVC4 makes no mention of changes in how #Html.ActionLink behaves.
I hate answering my own question, but #Matt Bodily put me on the right track.
The #Html.Action method actually invokes a controller and renders the view, so that wouldn't work to create a snippet of HTML in my case, as this was causing a recursive function call resulting in a StackOverflowException. The #Url.Action(action, controller, { area = "abc" }) does indeed return the URL, but I finally discovered an overload of Html.ActionLink that provided a better solution for my case:
#Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
Note: , null is significant in this case, to match the right signature.
Documentation: #Html.ActionLink (LinkExtensions.ActionLink)
Documentation for this particular overload:
LinkExtensions.ActionLink(Controller, Action, Text, RouteArgs, HtmlAttributes)
It's been difficult to find documentation for these helpers. I tend to search for "Html.ActionLink" when I probably should have searched for "LinkExtensions.ActionLink", if that helps anyone in the future.
Still marking Matt's response as the answer.
Edit: Found yet another HTML helper to solve this:
#Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
How I redirect to an area is add it as a parameter
#Html.Action("Action", "Controller", new { area = "AreaName" })
for the href portion of a link I use
#Url.Action("Action", "Controller", new { area = "AreaName" })
Just to add up my bit:
Remember, you're gonna need to have at least 2 areas in your MVC application to get the routeValues: { area="" } working; otherwise the area value will be used as a query-string parameter and you link will look like this: /?area=
If you don't have at least 2 areas, you can fix this behavior by:
1. editing the default route in RouteConfig.cs like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
OR
2. Adding a dummy area to your MVC project.
Below are some of the way by which you can create a link button in MVC.
#Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)
#Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })
#Html.Action("Action", "Controller", new { area = "AreaName" })
#Url.Action("Action", "Controller", new { area = "AreaName" })
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a>
Hope this will help you.
I am working in Asp.net mvc3 application.I have created url for product detail page like this
routes.MapRoute(
"ProductDetail",
"{category}/{title}-{id}",
new { controller = "ProductDetail", action = "Index" }
);
for other controller using this
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Following code creating this url
www.example.com/Shoes/blackshoes-100
Now Problem is that i want to use this url for ProductDetail page if add any other controller and action name it will redirect to ProductDetail page like this
www.example.com/Home/Index-100
How can i restrict this url for ProductDetail Page?
is this right way to do this?
I wan to hide Controller and Action of Productdetail page.
Category,title and id values are changing for every product.
You have to define routes for any other page you have and map those routes before you map your peoduct detail route. Then the route maching mechanism will find them first and use them.
Of course you do not have to map route for every single action. You can create some prefixes for example for diffrent controllers like example below, to catch all routes for Home controller actions:
routes.MapRoute(
"Home",
"Home/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
Could someone show me how to use the MapRoute method? I have tried creating my own routes, but it's not working. What i want to accomplish is a route that routes "http://servername/home/default.aspx" into controller "Home" and action "Default". Also, would it be possible to say that if the user is browsing the default.aspx "file", it would actually point to the "Index" action?
I have tried reading the MSDN references and googling, but it didn't make me any wiser.
Probably too late to help the developer who raised the question but may help someone else. New to MVC but what I found is the map routes seem to be processed in the order they are added. I had a similar problem, my specific route was not working until I started adding the default route as the last route.
If the default map route is added before your custom one and your custom URL matches the structure defined by the default map route you will never reach your custom route.
The route you want to configure the first part of your question is:
routes.MapRoute(
"",
"home/default.aspx",
new { controller = "Home", action = "Default" }
);
Assuming you wish to 'browse' default.aspx with some sort of parameter you can do something like:
routes.MapRoute(
"",
"home/default.aspx/{param}",
new { controller = "Home", action = "Default", param = UrlParameter.Optional }
);
And you would then need to create your Default action to accept string param.
You also have to make sure the parameter name is the same as the action's parameter name.
Example:
routes.MapRoute(
name: "MyName",
url: "{controller}/{action}/{myParam}",
defaults: new { controller = "MyController", action = "MyAction", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
MyController:
public ActionResult MyAction(string myParam = "")
{
}