Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I use one form or one per table row asp.net mvc

I just caught myself doing this:

<table>
   <tr>
      <th>Code</th>
      <th>Enabled</th>
      <th>Percentage</th>
      <th>Amount</th>
      <th>Start</th>
      <th>End</th>
      <th>Action</th>
   </tr>
   @foreach(var item in Model)
   {
      <tr>
         <td>@Html.ActionLink(item.Code, "Edit", new { id = item.Id })</td>
         <td>@item.Enabled ? "Yes" : "No"</td>
         <td>@item.Percentage</td>
         <td>@item.Amount</td>
         <td>@item.StartDate</td>
         <td>@item.EndDate</td>
         <td>
            @using (Html.BeginForm("Delete", "Discounts", new { id = item.Id }))
            {
               <input type="submit" value="Delete" />
            }
         </td>
      </tr>
   }
</table>

The reason I stopped was because I have a form in every row, as a good practice would it be better to have the entire table wrapped in a single form instead?

I probably already know the answer but thought I'd check :-)

like image 620
Mantorok Avatar asked Nov 11 '11 14:11

Mantorok


2 Answers

I would say it depends on your particular scenario.

  • If you need to minimize page size, you might go for one form. However, then you would need to use javascript to update some (hidden) field before submitting the form.
  • On the other hand, your current approach works even if the user has turned javascript off

Based on my current knowledge of your situation I would probably go with what you have now, just because it is nice and clean.

like image 52
Rune Avatar answered Oct 10 '22 08:10

Rune


I think your approach is fine and is often the best way. e.g. if you were writing an app with a voting system like stackoverflow (example chosen because you are looking at such an app right now) and you wanted to implement the voting mechanism by using HttpPost then you might create a small control with the up and down buttons as separate forms*. That way you could easily add any number of such "widgets" to a page and the containing page wouldn't need to know anything about them (including if they were even present). Indeed, you could use unobtrusive javascript to submit the form and reload the vote "widget" with a failback to reload the page if javascript was turned off and it could all look pretty nice.

*NOTE: I don't think that's how they do it at stackoverflow, mind you!

Non-AJAX failback could be like this:

[HttpPost]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult DoThing(whatever params you are passing in)
{
  // Do stuff and then...
  if (Request.IsAjaxRequest)
  {
      return View("_partialThingView", thingViewModel);
  }
  else
  {
      RedirectToAction("Index");
  }
}
like image 2
Tom Chantler Avatar answered Oct 10 '22 10:10

Tom Chantler