Home > Enterprise >  Transfer value from view to controller
Transfer value from view to controller

Time:03-24

I've been trying to pass and id of an user to my controller from a view. I've been using ActionLink in view and ActionResult in controller. Nothing seems to help. I've also tried Html.BeginForm but it didn't work as well. In both cases i get a Resource Not Found error in the end.

Here is my controller function:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ApproveUser(int id)
{
    UserDTO user = new UserDTO();
    user = userService.GetUser(id);
    user.Approved = true;
    userService.Update(user);
    return RedirectToAction("Index");
}

Here is my view (ActionLink):

@foreach (var item in Model.Users)
{
    if (item.Approved == false)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Login)
            </td>
            <td>
                @Html.ActionLink("Approve",  "ApproveUser", "AdminController", new { id = item.Id }, null)
            </td>
        </tr>
    }
}

This is the screenshot of the error:

https://i.imgur.com/cvdSYg1.png

CodePudding user response:

You want to pass an id using @Html.ActionLink. You can do this in this way:

First specify the correct route, you have mentioned AdminController as Controller parameter. You only need to specify Admin there. Change your id to a more specific term like itemid. The id can confuse the route.

@foreach (var item in Model.Users)
{

    if (item.Approved == false)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Login)
            </td>
            <td>
                @Html.ActionLink("Approve", "ApproveUser", "Admin", new { itemid = item.Id }, null)
            </td>
        </tr>
    }
}

Remove the attributes from your Controller method since default verb is HttpGet and that is what you are doing here. There is no need for ValidateAntiForgeryToken attribute since you are not generating it firstly and it is used for POST requests during form submission.

public ActionResult ApproveUser(int itemid)
{
    UserDTO user = new UserDTO();
    user = userService.GetUser(itemid);
    user.Approved = true;
    userService.Update(user);
    return RedirectToAction("Index");
}
  • Related