views:

18

answers:

2

Is it possible to submit a form on a view to the controller with a parameter?

My controller action is:

public ActionResult Index(BusinessObject busObj, int id = 0){
    return RedirectToAction("Index", new {businessObj = busObj, search = id });
}

I have a submit button, but i also have dropdownlists that post back to the controller so that the values can be filtered. I am trying to distinguish between the events using the id parameter. My intuition tells me that this involves routing, but im not sure what approach to take. Insight is welcome :D

A: 

Take a look at ActionFIlters

Bryce Fischer
+1  A: 

Your question is not very clear. A form already contains parameters that will be sent to the controller action. So as long as you include the id parameter either at the form action or inside the form, it's value will be sent.

Example as route parameter:

<% using (Html.BeginForm("Index", "Home", new { id = "123" })) { %>
    ...
<% } %>

And as input field:

<% using (Html.BeginForm("Index", "Home", FormMethod.Post)) { %>
    <%= Html.Hidden("id", "123") %>
<% } %>
Darin Dimitrov
Ill try to elaborate. When the form is submitted by the search button, i want the id parameter on the controller action to be for example, 1. Whereas, when a dropdownlist change event occurs, i want it to be 0 (or null).
John Stuart
When a dropdownlist event occurs, the form won't be submitted automatically. You need to submit it yourself. This means that you need to write javascript and subscribe to the change event of the dropdown. Then you could simply set the value of the hidden field to 0 before submitting the form.
Darin Dimitrov
The top example you have, i thought the new{ id = "123"}} is setting the identification of the form, not the routing parameter. At least, in my code im using it as the identification for when i use JQuery to catch dropdownlist.change and button.submit events. Could you elaborate on how to use this?
John Stuart
The top example sets the route parameter. It should generate something similar to this: `<form action="/Home/Index/123" method="post">` if you use default routing.
Darin Dimitrov
So, if im using jquery or javascript how would i change the form's id when its being submitted?
John Stuart
It's easier if you were using a hidden field. You could simply `$('#id').val('0');`. If you take the first example you will need to modify the `action` attribute of the form and replace the last part with `0`. The problem with this approach is that if you decide to later change your routing rules, javascript will break. That's why I would recommend you using a hidden field in this case. By default you could set it's value to 1 and when the dropdown changes you change to 0.
Darin Dimitrov
Just got it working. You're a lifesaver!
John Stuart