0

I'm trying to figure out how to post the same form multiple times with an ID parameter, depending on which button is clicked. The problem I'm having is that the form only posts when the first button is pressed, but no other buttons makes the form post.

@using (Html.BeginForm())
{
  foreach (var p in ViewBag.Projects)
  {
  <form role="form" id="frm">
  <input type="hidden" value="@p.projId" name="projid" />
  <p>@p.name <input type="submit" value="Add user" 
  class="btn btn-default btn-xs" id="btn-add" /></p>
  </form>
  }
}

I want to post the ID of the project when the button listed next to that project is pressed. My postfunction looks like this:

 [HttpPost]
    public ActionResult projects(int projid)
    {
        //testing
        TempData["title"] = projid.ToString();
        ViewBag.Projects = repo.GetAllProjectsForUser(User.Identity.Name);
        return View();
    }

Thanks for any help! The solution is probably easier than I think, starting to confuse myself :)

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

0

You have nested forms which is invalid and not supported. You need to remove the outer Html.BeginForm(). Your also furter generating invalid html because of the duplicate id attributes you add in the submit button. Since you not editing any values, you do not need the hidden input and instead can add the value of projId to the route parameters

@foreach (var project in ViewBag.Projects)
{
  using (Html.BeginForm(new { projid = project.projid })) // add projid as a route value
  {
    <p>
      @project.name
      <input type="submit" value="Add user" class="btn btn-default btn-xs" /> // remove the id attribute
    </p>
  }
}
  • THANK YOU! It works like a charm now. I wasn't paying attention to how I nested the forms, and didn't realize I could add it to the route in that manner. – Viktor Gullmark Oct 02 '15 at 02:01