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
2010-09-20 19:11:28
It's been a while since I've done MVC programming though, so I might be talking out of my bit bucket :-)
John Bledsoe
2010-09-20 19:12:24
Thanks, no parameters does work! But how do I specify POST or GET?
JoelFan
2010-09-20 19:21:23
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
2010-09-20 19:38:36
@Dismissile, but what controllerName and actionName to I use?? I want to submit back to the same action
JoelFan
2010-09-20 19:45:51
By default BeginForm() specifies POST so you don't need to specify that.
BuildStarted
2010-09-20 19:47:59
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
2010-09-20 20:03:55
@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
2010-09-20 20:37:21
@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
2010-09-20 20:40:39
@bzlm... no... I've been surfing theOnion, xkcd, dilbert, and theDailyWtf and periodically checking back here
JoelFan
2010-09-20 21:11:56
@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
2010-09-21 07:33:03
+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
2010-09-20 22:00:21
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
2010-09-21 12:32:07