簡體   English   中英

從視圖將字符串傳遞給控制器​​/動作

[英]passing string to controller/action from view

我試圖通過單擊視圖中的鏈接來降低用戶的角色。

當我單擊鏈接時,它不會轉到操作,但只會顯示404錯誤,並將找不到的資源與我嘗試傳遞給操作的字符串鏈接(稱為“ stringparameter”)

在這種情況下,鏈接為/ 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");
    }

這是視圖模型

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

這是視圖(視圖中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/Disable?id=@item.UserId">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>
}

這是因為href在ATTR a元素只是不GETPOST ,所以它的工作原理改變行動:

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

但我建議您使用JS執行此操作。

只需刪除[HttpPost],它說該控制器只能通過POST方法訪問,而您正嘗試通過GET訪問,則應讓它發布並使用AJAx進行調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM