简体   繁体   English

在MVC 2中的Html.ActionLink中传递字符串

[英]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. 我已经完成了MVC音乐商店应用程序,现在我正在为练习做自己的修改,也为我准备在工作中完成类似的任务做好了准备。

What I have done, is create a view that displays the 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: 我在global.asax.cs文件中注册了以下路由,但我不确定我是否已正确完成:

routes.MapRoute(
    "AdminPassword", //Route name
    "{controller}/{action}/{username}", //URL with parameters
    new { 
        controller = "StoreManager", 
        action = "changeUserPassword", 
        username = UrlParameter.Optional
    });

Here is my GET action: 这是我的GET操作:

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. 我已通过代码调试,发现ViewData [“username”] =用户名没有填充,所以看起来我没有正确注册路由,或者我根本无法使用像我这样的actionlink传递用户名。

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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM