Reputation: 69
I would like to post between 55 and 100 items which could be false or true from view to my controller without using Model. This is my code in Razor View:
@using(Html.BeginForm( "User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
{
<input type="checkbox" name="U1">Choice one</input>
<input type="checkbox" name="U2">Choice two</input>
<input type="checkbox" name="U3">Choice three</input>
<input type="checkbox" name="U4">Choice four</input>
....
<input type="checkbox" name="U55">Choice fifty five</input>
<button type="submit">Send</button>
}
Controller:
[HttpPost]
public async Task<ActionResult> User(Array....)
{
return view();}
How can I send all of parameters (checkboxes) using an array to my controller. I appriciate all your solutions.
Upvotes: 1
Views: 2270
Reputation: 9054
Dynamically you can do it like bellow code:
@using(Html.BeginForm( "User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
{
<input type="checkbox" name="answer[]" value="@dynamicValue">@dynamicValue</input>
<button type="submit">Send</button>
}
and
[HttpPost]
public async Task<ActionResult> User(string[] answer)
{
}
Upvotes: 3
Reputation: 2525
TBH it is better to use model for binding.
However, since you explicit say you don't want to then, this would be how to do it without specific model
in your razor view, give each checkbox same name (also same as the parameter name in your action) and a value
such that:
@using(Html.BeginForm( "User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
{
<input type="checkbox" name="answer" value="U1">Choice one</input>
<input type="checkbox" name="answer" value="U2">Choice two</input>
<input type="checkbox" name="answer" value="U3">Choice three</input>
<input type="checkbox" name="answer" value="U4">Choice four</input>
....
<input type="checkbox" name="answer" value="U55">Choice fifty five</input>
<button type="submit">Send</button>
}
Then in your action:
[HttpPost]
public async Task<ActionResult> User(string[] answer)
{
}
if say user checked One
, two
and four
, then in your answer
parameter you will get U1
, U2
and U4
Then base on the value in answer
, you can determine each question's true or false
Upvotes: 0