tags:

views:

71

answers:

3

In my View (.aspx) code, what parameters can I provide to Html.BeginForm() in order to get it to submit back to the same controller and action that produced the view?

+4  A: 

It all depends on your route table. Assuming that you're using standard routes, I think you can provide no arguments (or nulls) and that you'll end up at the same controller-action that generated the view.

Otherwise, you can pull the current controller and action from the route data.

John Bledsoe
It's been a while since I've done MVC programming though, so I might be talking out of my bit bucket :-)
John Bledsoe
Thanks, no parameters does work! But how do I specify POST or GET?
JoelFan
In order to specify the method (POST/GET) you will have to use one of the other method signatures. BeginForm(string actionName, string controllerName, FormMethod formMethod) should do the trick.
Dismissile
@Dismissile, but what controllerName and actionName to I use?? I want to submit back to the same action
JoelFan
By default BeginForm() specifies POST so you don't need to specify that.
BuildStarted
You'd have to specify it. You know what the controller name and action name are going to be I would assume? If you have a ProductsController class and specify a Details action method. If you generate a Details view off of that, you would specify BeginForm("Details", "Products", FormMethod.Post)
Dismissile
@Dismissile... no I don't know what they are... That is the point of this question... I want to post back to "submit back to the same controller and action that produced the view"
JoelFan
@JoelFan Surely during this past hour you've done some experiments with "pull the current controller and action from the route data" as suggested in this answer. How did that go?
bzlm
@bzlm... no... I've been surfing theOnion, xkcd, dilbert, and theDailyWtf and periodically checking back here
JoelFan
@JoelFan Good call - BuildStarted did the final bit of research for you while you were busy trolling: http://stackoverflow.com/questions/3754622/submit-to-same-action-in-mvc/3755856#3755856
bzlm
+1  A: 

Using the ViewContext you can get the route data that was called

<% using (Html.BeginForm(ViewContext.RouteData.Values["controller"].ToString(), ViewContext.RouteData.Values["action"].ToString(), FormMethod.Post)) {%>
    your form data here
<% } %>
BuildStarted
A: 

In your view

<% using (Html.BeginForm("actionName", "controllerName", new {  }, FormMethod.Post, "")){ %>
<%} %>

if you are not using html helpers

<form id='form' action="../controllerName/actionName" method="post">

In your controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult actionName (FormCollection collection)
{}
Kanishka