Reputation: 466
I have the following class:
public class Entidade
{
public string Voz { get; set; }
public bool Valor { get; set; }
}
I generate the View (GET) with the controller:
public IActionResult Entidade()
{
var model = GetVoidEntidade.Entidades();
return View(model);
}
Where GetVoidEntidade.Entidades() will generate a List of "Entidade" with 5 rows, each of them having an "Entidade" with a unique string for "Voz" and "Val" will be false.
The View:
<form asp-action="Entidade">
@{
int i = 0;
}
@foreach (var entidade in Model)
{
var name = $"Valor[{i++}]";
<input type="checkbox" value="@entidade.Valor" class="form-check-input" name=@name />@entidade.Voz<br />
}
<div class="form-group">
<input type="submit" value="Próximo" class="btn btn-success align-content-end float-md-right" />
</div>
</form>
The POST controller is just there so that I can, trough the debugger pick the return:
[HttpPost]
public IActionResult Entidade([FromBody]IEnumerable<Entidade> model)
{
var boh = Request.Form.Files;
return View();
}
When I run it and try to execute the POST I get a message of error 405: Method Not Allowed, and sure enough, don't get the data.
How can I receive the data from the Check Box into the controller?
Upvotes: 0
Views: 66
Reputation: 239240
[FromBody]
means you're sending something like application/json
or application/xml
. An HTML form sends as x-www-form-urlencoded
or multipart/form-data
. Remove the [FromBody]
attribute from the action param. That solves your immediate problem, but afterwards, you're just going to get an empty model because your input names are not correct.
First, you need to use a for
rather than a foreach
, as you need to index the list. Second, the name you're generating currently isn't even remotely correct. It would need to be something like: [N].Valor
where N
is the index. Third, you should just use the tag helper so you don't even need to think about it. In other words, you code should be:
<form asp-action="Entidade">
@for (var i = 0; i < Model.Count; i++)
{
<input asp-for="@Model[i].Valor" type="checkbox" class="form-check-input" />
@entidade.Voz<br />
}
<div class="form-group">
<button type="submit" class="btn btn-success align-content-end float-md-right">Próximo</button>
</div>
</form>
Upvotes: 2
Reputation: 469
name element should be same for all item in the same group
@foreach (var entidade in Model)
{
//var name = $"Valor[{i++}]";
<input type="checkbox" value="@entidade.Valor" class="form-check-input" name="StaticName" />@entidade.Voz<br />
}
Upvotes: 0