41

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
  • 72,564
  • 26
  • 147
  • 178
mrblah
  • 93,893
  • 138
  • 301
  • 415

4 Answers4

65

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.

Jonathan Freeland
  • 4,905
  • 3
  • 27
  • 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. – Jonathan Freeland 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,494
  • 3
  • 33
  • 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
  • 17,649
  • 21
  • 81
  • 115
Rich
  • 71
  • 1
  • 2
0
<!-- ACTION: Category/Update/Id | Method:Post-->
@using (Html.BeginForm("Update", "Category",new {Id = @Model.Id },FormMethod.Post)){}
rohit.khurmi095
  • 661
  • 8
  • 7