42

In ASP.NET MVC I'm using the HTML helper

Html.BeginForm("ActionName", "Controller", FormMethod.Post);

But I need to post to: /controller/action/23434

How do I pass in the ID?

Matt
  • 74,352
  • 26
  • 153
  • 180
mrblah
  • 99,669
  • 140
  • 310
  • 420

4 Answers4

66

Matt's should work fine. If you are still passing in FormMethod.Post, though, you need to do it like this:

Html.BeginForm("action","controller", new { Id = 12345 }, FormMethod.Post);

Reversing the third and fourth parameters will result in the Id being treated as an attribute instead of a route value.

Jon
  • 4,925
  • 3
  • 28
  • 38
  • I am losing the existing route values when I am using this method. Say my url was `/controller/action?type=golden`, the form target (using your way) now becomes `/controller/action/12345` while I want it to be `/controller/action/12345?type=golden`. Do you know any way I could preserve the existing route values and append my own too? – Arnab Chakraborty Mar 27 '12 at 07:07
  • 1
    @Aki Try adding `type` as a hidden field within the form and it should get sent along. – Jon Mar 27 '12 at 13:34
  • I could, but you see that's not my problem. Its not necessary that I have only `type` in my query string, I could have N number of params, which might be different in different actions. It would be a real pain to go into all those actions and add the query params as hidden fields. – Arnab Chakraborty Mar 28 '12 at 03:22
10

Html.BeginForm("action", "controller", new {Id = 12345})

Matt Hinze
  • 13,577
  • 3
  • 35
  • 40
7
Html.BeginForm("action", "controller", new { id = ViewBag.FileID },
FormMethod.Post, new { id = "feedbackform" })

As for the querystring, ?type=golden, I don't know how to do that. Of course, a querysting is a get, and undermines the whole purpose of FormMethod.Post. I mean, you could use FormMethod.Get, if you want querystring data, and this might be what you are looking for.

Additionally, you can avoid html.beginform and do the querystring, get + post, manually with a form tag.

Thirdly, if you are using the form, you can make a hidden field:

[input type=hidden name="type" value="golden"]

Then, when the submit button is pressed the value is passed properly as a form variable.

Paolo
  • 20,112
  • 21
  • 72
  • 113
Rich
  • 71
  • 1
  • 2
0
<!-- ACTION: Category/Update/Id | Method:Post-->
@using (Html.BeginForm("Update", "Category",new {Id = @Model.Id },FormMethod.Post)){}
rohit.khurmi095
  • 2,203
  • 1
  • 14
  • 12