How to submit form with multi buttons with same value asp.netMvc
I need to build voting web site so, I have couple c开发者_StackOverflow社区andidates and below them a vote button, how I can find which of the buttons was submitted
thanks
Give each of your buttons a name, like so (notice they are both "submit" buttons)::
<input type="submit" name="buttonYes" value="Yes" />
<input type="submit" name="buttonNo" value="No" />
Then, in your controller, capture a parameter for each of the two button names like this:
public ActionResult Index(string buttonYes, string buttonNo) { ... }
You can then tell which button was pressed by checking to see which of these two parameters is not null; the one which is pressed with a have a value equal to the "value" attribute of the button, the other one will be null:
if (buttonYes != null)
{
// Then the yes button was preseed
}
else if (buttonNo != null)
{
// Then the no button was pressed
}
else
{
// Neither button was used to submit the form
// and we got here some other way
}
The reason this works is because the web browser sends the information for the submit button that was pressed as part of the HTTP post to the web server. The button that was not pressed will not be sent with the post, and therefore the parameter will be null.
There are lots of ways to rewrite and optimzie this, but this is the essence of it and shows the fundamentals that are at work--you can play with it from there.
I wouldn't use the button value, I would set it up so that the url used to do the post encodes the vote itself. You could do this a couple of ways.
Use links
<div class="left">
<img src="/images/candidate/@Model.Candidates[0].ID" alt="@Model.Candidates[0].Name" />
@Html.ActionLink( "Vote for " + Model.Candidates[0].Name, "count", "vote" )
</div>
<div class="right">
<img src="/images/candidate/@Model.Candidates[1].ID" alt="@Model.Candidates[1].Name" />
@Html.ActionLink( "Vote for " + Model.Candidates[1].Name, "count", "vote" )
</div>
Use separate forms
<div class="left">
@using (Html.BeginForm( "count", "vote", new { id = Model.Candidates[0].ID } ))
{
<img src="/images/candidate/@Model.Candidates[0].ID" alt="@Model.Candidates[0].Name" />
<input type="submit" value="Vote" />
}
</div>
<div class="right">
@using (Html.BeginForm( "count", "vote", new { id = Model.Candidates[1].ID } ))
{
<img src="/images/candidate/@Model.Candidates[1].ID" alt="@Model.Candidates[1].Name" />
<input type="submit" value="Vote" />
}
</div>
Either of the above can be adapted to work with AJAX as well. Note, if you care, you'll need to build in some mechanism to detect vote fraud, e.g., add a one-time nonce to the url to verify that it isn't used more than once; track the number of times a user has voted if they are authenticated, etc.
精彩评论