Passing multi parameters from view to controller using array - c#

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.

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)
{
}

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

Related

Form is submitting to an unexpected endpoint, even though asp-action is set correctly on the form element

The first case works
In the second case, I made 2 changes from
<form method="post" asp-action="Delete">
to
<form method="post" asp-action="DeleteConfirmed">
and removing [ActionName("Delete")] and now the deletion fails.
Case 1
<form method="post" asp-action="Delete">
<input type="submit" asp-route-id="#Model.Id" value="Delete" />
</form>
public async Task<IActionResult> Delete(int id)
{
// intentionally removed for simplicity
}
[HttpPost]
[ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
// intentionally removed for simplicity
}
Rendered HTML before form posting:
<form method="post" action="/Home/Delete/3">
<input type="submit" value="Delete" formaction="/Home/Delete/3" />
Case 2
<form method="post" asp-action="DeleteConfirmed">
<input type="submit" asp-route-id="#Model.Id" value="Delete" />
</form>
public async Task<IActionResult> Delete(int id)
{
// intentionally removed for simplicity
}
[HttpPost]
//[ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
// intentionally removed for simplicity
}
Rendered HTML before form posting:
<form method="post" action="/Home/DeleteConfirmed">
<input type="submit" value="Delete" formaction="/Home/Delete/3" />
Question
What causes this?
I'd suggest setting asp-action of the submit button:
<input type="submit" value="Delete" class="btn btn-danger form-control"
asp-route-id="#Model.Id" asp-action="DeleteConfirmed"
onclick="return confirm('Are you sure you want to delete this category?');"
/>
So it knows to submit to the correct POST endpoint.
This is necessary since you have set the asp-route-id, as per this comment:
When you add an asp-route-id on a submit button, it independently
determines the Action it would route to. It does not work in tandem
with the values you specified in form. If you're attempting to post to
two different actions from a single form, using the "working" sample
(which is what I have suggested) would be the way to go. Alternatively, specifying all the route values on
the form tag would be the way to go:
<form asp-action="DeleteConfirmed" asp-route-id="1">
<input type="submit" /> </form>

Is it possible to know which of two submit buttons are clicked?

I am thinking of having something like this:
#if(Model.ShowSubmitButton)
{
<input id="submitButton" type="submit" value="Update stuff" />
}
else
{
<input id="continueButton" type="submit" value="Continue to next page" />
}
Then in controller is it possible to know which button it is getting called from?
I originally had my controller method working with the first button, now adding a second button with different functionality, wanted to see if using the same method I can determine which button was clicked ? and if it is not possible this way, then what do you suggest?
Not without extra information. I would likely split them up rather than have two submit buttons for the same form doing two different things but if you really want to go down that road one way would be to add an additional posted variable that tells you which was clicked.
#if(Model.ShowSubmitButton)
{
<input type="hidden" name="submitStyle" value="update"/>
<input id="submitButton" type="submit" value="Update stuff" />
}
else
{
<input type="hidden" name="submitStyle" value="continue"/>
<input id="continueButton" type="submit" value="Continue to next page" />
}
To answer your additional question. Either you can add this variable to your model posted back or add it as an additional parameter.
// Where "MyModel" has a public property "SubmitStyle"
public ActionResult MyAction(MyModel model)
// Or an int, string, whatever type of parameter you want/need.
// In my example it was a string so...
public ActionResult MyAction(string submitStyle/*, <other params...>*/)
You could add a hidden field. Not ideal solution, but does the job.
#if(Model.ShowSubmitButton)
{
<input type="hidden" name="buttonClicked" value="1">
<input id="submitButton" type="submit" value="Update stuff" />
}
else
{
<input type="hidden" name="buttonClicked" value="2">
<input id="continueButton" type="submit" value="Continue to next page" />
}
In your controller you would accept it as:
public ActionResult MyAction(MyObject myobj, int buttonClicked)
There is an elegant way (tested only on chrome yet), define two inputs
<input type="submit" value="Next" name="Action"/>
<input type="submit" value="Prev" name="Action"/>
Now in you input model in controller put model defined like this:
public class MyModelDto
{
// other properties
public MyCustomAction Action { get; set; }
}
Where the
public enum MyCustomAction
{
Next=0,
Prev=1
}
Now check the value of action.

HTML checbkox values to C# array

I have list of html checboxes in form and I need get checked checboxes values to C# array after form sent, it is possible?
<form id="form1" action="" method="post">
#foreach (var category in ViewBag.Categories)
{
<ul>
<li>
<input type="checkbox" name="Category" value=#category["UUID"] />#category["CategoryName"]<br /> //Generate >20 checkboxes
</li>
</ul>
}
<button type="submit" formmethod="post">Search</button>
</form>
First of all change following line:
<input type="checkbox" name="Category" value=#category["UUID"] />#category["CategoryName"]<br />
to:
<input type="checkbox" name="Category" value="#category["UUID"]"/>#category["CategoryName"]<br />
and now in your action you can get it from Request object or by adding a parameter of name Category to get in the action:
[HttpPost]
public ActionResult SomeAction()
{
var checkedCategories = Request.Form["Category"];
}
or:
[HttpPost]
public ActionResult SomeAction(int[] Category)
{
}
<input type="checkbox" name="Category" value=#category["UUID"] runat="server" />#category["CategoryName"]<br />
include runat="server" in the input type. you can acess in the code behind.

Posting List<Object> to a webapi 2

I have created a webapi as follow
public OatherResponse Post([FromBody] List<Oather> oather)
{
Note that OatherResponse and Oather both are classes having some property.
Now I am trying to test this using simple html as below
<form method="post" action="http://localhost:50813/api/RegisterOather">
<input type="text" name="oather[0].OatherName" id="oather[0].OatherName" value="a3VsZGVlcA==" />
<input type="text" name="oather[1].OatherName" id="oather[1].OatherName" value="a3VsZGVlcA==" />
<input type="submit" value="Click Here" />
</form>
OatherName is a string property in Oather class. But I always get count of oather as zero.
Am I missing something.
The name attribute values should be
name="[0].OatherName"
name="[1].OatherName"

How to send text from the textbox to the actionResult?

I have a question about MVC4 (Razor). I have page where I want to filter data. There is a textbox (input) and a submit button. I want to move the text in the textbox to the actionresult. How can I resolve this?
On my page I've the following row:
#{ using (Html.BeginForm("Experiences"))
{
<span class="label">Filter on:</span><input id="FilterText" type="text" size="50"/>
<input type="submit" value="Submit" name="knowledge" /><br />
}
}
<br />
And I want to call the ActionResult Experiences
public ActionResult Experiences(string knowledge = "")
{
ReadExperienceData(knowledge);
return View(ListOfExperiences);
}
Specify the name property value of the input element same as the action method parameter name.
<input id="FilterText" name="knowledge " type="text" size="50"/>
<input type="submit" value="Submit" name="submitKnowledge" />
Also it looks like you are not using the Beginform method properly. You may try any of the below overloads, as needed
#using(Html.Beginform("Knowledge","YourControllerName"))
{
//form elements
}
or
#using(Html.Beginform())
{
//form elements
}

Categories