Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from View to Controller

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?

like image 206
Pompair Avatar asked Jul 17 '26 23:07

Pompair


1 Answers

The simplest option would probably be a hidden input:

<input type="hidden" value="<%=mm.Key%>" name="key" id="key" />

(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).

like image 160
Marc Gravell Avatar answered Jul 19 '26 14:07

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!