C # MVC5 - Table with CheckBox and Different Actions

3

I'm working on a project where I have a page that lists some records, of which I'll 'thumb' some to perform batch actions, such as exclusion, status change, etc.

How do I send this list of my records to different actions?

My list is built like this:

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<table>
    <tr>
        <th>Selecione</th>
        <th>Descrição</th>
    </tr>
    @for (int r = 0; r < Model.Count(); r++)
    {
    <tr>
        <td>@Html.CheckBoxFor(i => i[r].Selecionado)</td>
        <td>@Html.DisplayFor(i => i[r].Descricao)</td>
    </tr>
    }
</table>

<input type="button" value="Alterar Selecionados Para Status x" />
<input type="button" value="Alterar Selecionados Para Status y" />
<input type="button" value="Alterar Selecionados Para Status z" />
}

In my post method, I get the parameter as follows:

[...]
public ActionResult SelectLines(List<Objeto> list) { [...] }
    
asked by anonymous 30.07.2015 / 19:24

1 answer

2

The most elegant solution I know is to implement a submit button detection attribute of form :

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
    public string Name { get; set; }
    public string Argument { get; set; }

    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        var isValidName = false;
        var keyValue = string.Format("{0}:{1}", Name, Argument);
        var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);

        if (value != null)
        {
            controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
            isValidName = true;
        }

        return isValidName;
    }
}

Change your buttons to:

<input type="submit" value="Alterar Selecionados Para Status x" name="status:x" />
<input type="submit" value="Alterar Selecionados Para Status y" name="status:y"/>
<input type="submit" value="Alterar Selecionados Para Status z" name="status:z"/>

Controller would look like this:

[HttpPost]
[MultipleButton(Name = "status", Argument = "x")]
public ActionResult MudarParaStatusX(MeuViewModel mvm) { ... }

[HttpPost]
[MultipleButton(Name = "status", Argument = "y")]
public ActionResult MudarParaStatusY(MeuViewModel mvm) { ... }

[HttpPost]
[MultipleButton(Name = "status", Argument = "z")]
public ActionResult MudarParaStatusZ(MeuViewModel mvm) { ... }
    
31.07.2015 / 16:10