Passing a string in Html.ActionLink in MVC 2
I have completed the MVC Music Store application, and now am making my own modifications for practice, and also to prepare me to do similar tasks in my job.
What I have done, is create a view that displays th开发者_StackOverflow社区e current list of users. I have done this as I want to be able to change the passwords of users should they forget them. Here is a snippet from my view:
<% foreach (MembershipUser user in Model) { %>
<tr>
<td><%: Html.ActionLink(user.UserName, "changeUserPassword",
"StoreManager", new { username = user.UserName }) %></td>
<td><%: user.LastActivityDate %></td>
<td><%: user.IsLockedOut %></td>
</tr>
<% }%>
What I want to know, is it possible to pass the username through the actionlink as I have done above. I have registered the following route in the global.asax.cs file, however I am unsure if I have done it correctly:
routes.MapRoute(
"AdminPassword", //Route name
"{controller}/{action}/{username}", //URL with parameters
new {
controller = "StoreManager",
action = "changeUserPassword",
username = UrlParameter.Optional
});
Here is my GET action:
public ActionResult changeUserPassword(string username)
{
ViewData["username"] = username;
return View();
}
I have debugged through the code to find that ViewData["username"] = username doesn't populate so it looks like either I have not registered the routes properly, or I simply cannot pass the username using the actionlink like I have.
I'd be grateful if someone could point me in the right direction.
You seem to be using the wrong method signature, I think you're using this one
You want to do
Html.ActionLink(user.UserName, "changeUserPassword",
new { controller = "StoreManager", username = user.UserName });
Or you can do
Html.RouteLink(user.UserName, "AdminPassword",
new { username = user.UserName });
精彩评论