Reputation: 46780
I have a razor view with a BeginForm command and a loop within that in which I create a html table with a submit button in each row. My question is when I submit the form for a particular row back to the controller how do I ensure that I know which row that button relates to?
Thanks,
Sachin
Upvotes: 2
Views: 2906
Reputation: 1004
In your loop, just give a name (for example submittedButton) to your submit button and set it's value to the row identification.
@using(Html.BeginForm())
{
foreach(var row in myRows)
{
<input type="submit" name="submittedButton" value="@row.ID" />
}
}
In your controller define a string argument which it's name is the same as submit button's name (in this example submittedButton) like this:
[HttpPost]
public ActionResult YourController(string submittedButton)
{
// submittedButton contains ID of selected row
return View();
}
Upvotes: 3
Reputation: 14951
I used this solution from mkozicki which is great as it is not affected by localisation issues (some other methods rely on the value of the button, which may change due to localisation). How do you handle multiple submit buttons in ASP.NET MVC Framework?
EDIT: If I am displaying data in a table and just want to know which line I have chosen, I will often create an HTML form for each line. In other words have the Ajax.BeginForm
inside the foreach
block, then each form can contain the ID which is passed to the controller on postback. This works nicely too and is very simple.
Upvotes: 1
Reputation: 14874
What's in my mind is to set a hidden input before submitting the form by a javascript function.
If you use jquery it can be sth like this:
$("input:submit").click(function() {
$("hiddenInput").val(
$(this).closest("input[name*='yourPrimaryKey']").val()
);
});
it finds the value of an input containing the ID of a row which its button was clicked.
Upvotes: 2