c# - 从 View 将字符串传递给 Controller ​​/操作

标签 c# asp.net-mvc razor asp.net-mvc-5

我试图通过单击 View 中的链接来降低用户的角色。

当我单击链接时,它不会转到操作,但只会给出 404 错误,并链接未找到的资源与我试图传递给操作的字符串(称为“字符串参数”) )

在本例中,链接为/Admin/Disable/stringparameter

我认为我没有使用正确的重载,有人可以帮助我吗? 谢谢

这是 AdminController 中的操作

 [HttpPost]
    public ActionResult Disable(string id)
    {
        Role rol = new UserRepository().GetRole("Disabled");             
        new UserRepository().UpdateUser(id,rol.RoleId);
        return RedirectToAction("Users");
    }

这是 View 模型

public class UserSuperUserPM
{
    public UserClass User { get; set; }
    public List<UserClass> Users { get; set; }

    public UserClass SuperUser { get; set; }
    public List<UserClass> SuperUsers { get; set; }

    public UserClass Disabled { get; set; }
    public List<UserClass> Disableds { get; set; }

    public UserClass Inactive { get; set; }
    public List<UserClass> Inactives { get; set; }
}

这是用户类

public class UserClass
{
    public string UserId { get; set; }
    public string Username { get; set; }
    public string Role { get; set; }
}

这是 View ( View 中 4 个类似表中的 1 个)

@foreach (var item in Model.Users)
{
    <tr>
        <td class="col-md-4">
            @Html.DisplayFor(modelItem => item.Username, Model.Users)
        </td>
        <td class="col-md-4">
            @Html.DisplayFor(modelItem => item.Role, Model.Users)
        </td>
        <td calss="col-md-4">
--------Commented attempted links(none of them work correct)
            @*@Html.ActionLink("Disable", "Disable", new { Controller = "Admin", action = "Disable", id = item.UserId })*@
            @*<a href="~/Controllers/AdminController/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eaae83998b88868fd5838ed7aa839e8f87c4bf998f98a38e" rel="noreferrer noopener nofollow">[email protected]</a>">Disable</a>*@
            @*@Html.ActionLink("Disable","Admin", new { id = item.UserId },null)*@
            @*@Html.ActionLink("Disable", "Disable","Admin", item.UserId)*@

-------original attempted link
            @Html.ActionLink("Disable", "Disable", new { id = item.UserId})




        </td>
    </tr>
}

最佳答案

这是因为 a 元素中的 href attr 只执行 GET 而不是 POST,所以它的工作方式发生了变化行动:

[HttpGet]
public ActionResult Disable(string id)
{
    Role rol = new UserRepository().GetRole("Disabled");             
    new UserRepository().UpdateUser(id,rol.RoleId);
    return RedirectToAction("Users");
}

但我建议你用 JS 来做这件事。

关于c# - 从 View 将字符串传递给 Controller ​​/操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34538572/

相关文章:

c# - 错误与 if else 和 View 中的标记

c# - Windows 上的 .net core 3.0 忽略了 NO_PROXY

c# - WCF 比运行相同代码的 WebAPI 慢得多

c# - 回发时 MVC 列表为空

c# - 使用 while 循环时显示多行结果而不是一行

asp.net-mvc - 在 ASP.NET MVC3 中使用 Razor 的文件上传控件

c# - 如何在按钮单击事件上将数据从数据 GridView 加载到单独的窗口窗体?

c# - 在 Microsoft.Azure.Cosmos.Table 中使用 TableEntity.Flatten 的正确方法是什么?

css - ASP.Net MVC 响应式 Web 应用程序开发

c# - 如何根据 ASP.NET VNEXT MVC6 中给出的路径进行虚拟路由/重定向?