Select all tr ​​tables and send them to the controller using the checkbox in MVC 4

I want to use the checkbox to select multiple users and send the result to my controller.

At first I sent only the number of mobile users to the controller, but I needed to send more than the number, I need the number and username, my controller and my view look like this:

Somehow send the number and name, for example?

@using (Html.BeginForm("Enviar", "Home")) { <table id="myTable"> <thead> <tr> <th> <input type="checkbox" /> </th> <th>@Html.DisplayName("Nome")</th> <th>@Html.DisplayName("CANCELADO")</th> <th>@Html.DisplayName("Numero")</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> <input type="checkbox" name="CELULAR" value="@item.CELULAR" /> </td> <td name="Nome">@Html.DisplayFor(modelItem => item.NOME)</td> <td name="Email">@Html.DisplayFor(modelItem => item.CANCELADO)</td> <td name="Celular" value="@item.CELULAR">@Html.DisplayFor(modelItem => item.CELULAR)</td> </tr> } </tbody> </table> <input type="submit" value="Selecionar"/> } 

The controller that receives:

 [HttpPost] public ActionResult Enviar(String[] celular) { ..... return View(); } 
+3
source share
1 answer

When publishing collections, you must index them correctly. To do this, you should use a for foreach instead of foreach .

Also, why does your HttpPost accept String[] and not your model? First change this type of your model.

Assuming your model is: @model List<YourType>

Modify HttpPost to accept the following:

 [HttpPost] public ActionResult Enviar(List<YourType> model) { ..... return View(); } 

Now we will rewrite your foreach in for and use the CheckBoxFor helper. In addition, add HiddenFor fields for any properties that you want to see in the message:

 @for (int i = 0; i < Model.Count; i++) { <tr> <td> @Html.CheckBoxFor(m => m[i].CELULAR) </td> <td name="Nome"> @Html.HiddenFor(m => m[i].NOME) @Html.DisplayFor(m => m[i].NOME) </td> <td name="Email"> @Html.HiddenFor(m => m[i].CANCELADO) @Html.DisplayFor(m => m[i].CANCELADO) </td> <td name="Celular" value="@m[i].CELULAR"> @Html.DisplayFor(m => m[i].CELULAR) </td> </tr> } 
+6
source

Source: https://habr.com/ru/post/1486949/


All Articles