Can you use the HtmlHelper.Actionlink() method to create RESTful URLs? - asp.net-mvc

I have some code like this:
<a href="<%= Html.ActionLink(
e.Member.UserName,
"profile",
"members",
new {username = e.Member.UserName}, null) %>"/>
The links it generates look like this:
http://mywebsite.com/members/profile/?username=scottm
Is it possible to make the link this:
http://mywebsite.com/members/profile/scottm
without having to do this:
<%= e.Member.UserName %>

Yes, you just need to set up another route.
routes.maproute(
"Profiles",
"members/profile/{UserName},
new { controller = "Members", Action = "Profile", UserName = "" }
}

I think a route like this may work. Did you try it?
routes.MapRoute(
"DefaultRest", // Route name
"members/profile/{username}", // URL with parameters
new { controller = "Members", action = "Profile", UserName = "" } // Parameter defaults
);

Related

How to pass Area in Url.Action?

The problem in Html.ActionLink() is that you can't add additional html content inside the tag that it generates.
For example, if you want to add an icon besides the text like:
<i class="fa fa-users"></i> Go to Users
Using Html.ActionLink(), you can only generate:
Go to Users
So, to resolve this, you can use Url.Action() to generate only the URL inside the tag like:
// Here, Url.Action could not generate the URL "/admin/users". So this doesn't work.
<i class="fa fa-usesr"></i> Go to Users
// This works, as we know it but won't pass the Area needed.
<i class="fa fa-users"></i> Go to Users
So, how do you pass the Area using Url.Action()?
You can use this Url.Action("actionName", "controllerName", new { Area = "areaName" });
Also don't forget to add the namespace of the controller to avoid a conflict between the admin area controller names and the site controller names.
Something like this
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "Site.Mvc.Areas.Admin.Controllers" }
);
}
#Url.Action("{action}", "{controller}", new { Area = "areaname" });
#Html.ActionLink("LinkName", "{action}", "{controller}", new { area = "{areaname}" }, new { #class = "btn btn-cool" })
write area name as html attribute with anonymus object. you can use actionlink html helper extension method to achieve same thing.
If you want to create link for root controllers, it's enough to use this code:
Url.Action("ShowImage", "Page", new { Area = "" })
#Url.Action("{action}", "{controller}", new { Area = "areaname" });
#Html.ActionLink("LinkName", "{action}", "{controller}", new { area = "{areaname}"}, new { #class = "btn btn-cool" })
You can use above this

Mvc: Exclude id from url

I have the next foreach in my cshtml page, it allows to me iterate in each Model item
#foreach (var item in Model)
{
<div class="date">
#item.pubDate
</div>
<a href="#Url.RouteUrl("Details", new { action = "Details", controller = "News", id = item.id, title = item.title })">
<img src="some route" alt="some alt" />
</a>
}
so now it's working fine and each element inside foreach loop has an url with something like
http://something.com/News/Details/1/first-title
http://something.com/News/Details/2/second-title
It's possible create urls with something like
http://something.com/News/Details/first-title
http://something.com/News/Details/second-title
but i can still sending id parameter to my controller ?
Thanks in advance
Add another route:
routes.MapRoute(
name: "NewsTitleRoute",
url: "News/Details/{id}/{title}",
defaults: new {
controller = "News",
action = "Details",
id = UrlParameter.Optional,
title = UrlParameter.Optional
}
);
In your controller declare the details method like this, with the two parameters as optional:
public ActionResult Details(int? id, string title="")
{
}
That route configuration and Details method will work for:
http://something.com/News/Details/
http://something.com/News/Details/1
http://something.com/News/Details/first-title
http://something.com/News/Details/1/first-title
You can just pass the title property for id parameter.
#Url.RouteUrl("Details",
new { action = "Details", controller = "News", id = item.title})
Then set type of id parameter as string in your action method:
public ActionResult Details(string id)
Or you can create custom route like in von-v's answer. Just make sure it's above the default route.

Routing issue with MVC

I'm working with MVC 3 and have an issue. Instead of giving mydomain/mydirectory/item like I expected I get this:
mydomain/mydirectory/list?animal=quack.
Here's the route in the global
//Default route mapping
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = #"[^\.]*", action = #"[^\.]*" }
);
Code showing how I'm building the link:
<div id="main-content" title="AnimalBox" style="float:none;">
<% Html.DataList(Model.PriceListAnimals).Columns(7).Item(item =>
{
item.Template(galleryImage =>
{%>
<div style="margin-left:20px; line-height:150%;">
<span><%= Html.ActionLink(galleryImage.AnimalName,"List",new { #animal = galleryImage.AnimalName }) %></span>
</div>
<% });
}).Render(); %>
</div>
Any ideas?
You have to define a route for special case routing like your instance. Since you are passing 'animal' as a parameter, you should create a route to handle that instance. In your global.aspx (above the default route), create something like below:
routes.MapRoute(
"Animal", // A distinct Route name
"{controller}/{action}/{animal}", // URL with parameters
new { controller = "MyDirectory", action = "List"}
);
This will define a route to the MyDirectory controller on the action list which has an animal parameter which is NOT OPTIONAL. Defining routes is what enables you to generate clean URLs from the html helpers and other methods (redirect to action, etc).
The overload for Html.ActionLink is:
Html.ActionLink("linkText", "actionName", "controller", object routeValues, object HtmlAttributes)
From what you've said, mydirectory = controller, and List = action, correct? If so, try:
<%= Html.ActionLink(galleryImage.AnimalName, "List", "mydirectory", new { #id = galleryImage.AnimalName }, null) %>
this should produce:
quack

#Html.ActionLink not Rendering as Expected

I have this in my Global.asax.cs:
routes.MapRoute(
"User",
"User/{username}/{action}",
new { controller = "User", action = "Index", username = "*" }
);
Then on my _Layout.cshtml I have this code:
<ul id="menu">
#if (!String.IsNullOrEmpty(Context.User.Identity.Name))
{
<li>#Html.ActionLink("Home", "Home", new { controller = "User" }, new { username = Context.User.Identity.Name })</li>
}
</ul>
</div>
</div>
The thing is, it will render the link properly the first time it swings through here. (Link will be /User/rob/Home where "rob" is a username. If I navigate elsewhere on the page and then click back on my link, the link is rendered as /User/*/Home. When I step through the code, Context.User.Identity.Name is correct every time.
Am I missing something really basic here? I'm not sure what to search for.
That's exactly what you should expect given that route. You don't specify username in the route values dictionary but in the HTML attributes, so it takes the default from the route, *. You should be using the signature that allows you to specify both the controller and the action as strings with additional route values in the dictionary.
#if (!String.IsNullOrEmpty(Context.User.Identity.Name))
{
<li>#Html.ActionLink("Home", "Home", "User" new { username = Context.User.Identity.Name }, null )</li>
}

Html.ActionLink for non-standard routing

I have a route definition like this:
routes.MapRoute(
"Pagesize",
"{controller}/{action}/pagesize/{pagesize}",
new { controller = "Home", action = "Index", pagesize = 10 }
);
When I use
<%= Html.ActionLink("MyText", "myaction", new { pagesize = 10 }) %>
it renders as
MyText
I can understand I am misusing ActionLink since I have /pagesize/ in between. How can I correctly use it to create the link?
MyText
Please note that I am using mvc RC2 and no other helper libraries. The generic ActionLink no longer exists in RC2.
Try:
<%= Html.RouteLink("MyText", "Pagesize", new { controller = "Home", action = "Index", pagesize = 10 })%>
have you tried specifying the defaults in the map route command
routes.MapRoute("Pagesize",
"{controller}/{action}/pagesize/{pagesize}",
new {pagesize = 10 },
new { controller = "Home", action = "Index" });

Resources