In an ASP.NET MVC application, I’m making logic for Admin to accept or reject new members. I’m showing a list of members and two buttons Accept and Reject, like this:
<% foreach (var mm in (ViewData['pendingmembers'] as List<MyMember>)) %> <% { %> <tr><td>Username:<%=mm.UserName %></td><td> <tr><td>Firstname:<%=mm.FirstName %></td><td> ...etc... <tr> <td> <% using (Html.BeginForm('AcceptPendingUser', 'Admin')) { %> <input type='submit' value='Accept' /> <% } %> </td> <td> <% using (Html.BeginForm('RejectPendingUser', 'Admin')) { %> <input type='submit' value='Reject' /> <% } %> </td> </tr> <% } %>
So, the list of pending member data is in a list of MyMember-objects. Each MyMember object will be printed out member and two buttons are setup for the admin to either accept or reject a pending member.
Then, in the controller I’m separating the handling of those two input fields/forms, like this:
public ActionResult AcceptPendingUser() { // TODO: Add code to save user into DB and send welcome email. return RedirectToAction('Index'); } public ActionResult RejectPendingUser() { // TODO: Add code to remove user from PendingUsers list and send rejection email. return RedirectToAction('Index'); }
I would like to directly get the object next to the button the user pressed. How can I send the MyMember object from the View to the controller? Or how do I send perhaps a numeric index with button press? Maybe with a hidden field?
The simplest option would probably be a hidden input:
(name accordingly; in each form)
The two controller would then take an argument called ‘key’ (rename to suit). If you want to parse the object from multiple inputs, you’ll need a
ModelBinder. Of course, rather than 2*n forms, you might consider either query-string based urls, or use something like jQuery (or some other script helper) to submit the data without needing the forms (if script is available).