views:

37

answers:

2

Hi I have this code in my view..

<%=Html.DropDownList("ProductTemplate",new SelectList(Model.ProductTemplate,"Value","Text"))%>

I know if this dropdownlist box is in between BeginForm submit I can able to access the value in Controller using collection["ProductTemplate"];

if it is not in my beginForm still I can able to access this selected value in controller?

thanks

+2  A: 

You could use AJAX to send the value of the currently selected element to a controller action. This is pretty trivial with jQuery:

$.post('/home/foo', { productTemplate: $('#ProductTemplate').val() }, function(data) {
    alert(data.success);
});

And to access the selected value in your controller action simply use a parameter:

[HttpPost]
public ActionResult Foo(string productTemplate)
{
    // TODO: do something with the selected productTemplate
    return Json(new { success = true });
}
Darin Dimitrov
How to access this value in the controller Darin. thanks
@rockers, see my update, you could use an action parameter named `productTemplate`, which is the same name as the parameter sent in the AJAX request.
Darin Dimitrov
Thanks for your time Darin, My situation is something differnt..I have three grids in my view, each grid has beginform.. but on the top of the page I have thid dropdown list box..if I am going to keep this dorpdownlist box in first grid begin form in action result I can able to access the value, but I am not able to keep this dropdownlist box again in second beginfrom so to avoid that I thought of doing something like this is that right what I am thikning here?thanks
@rockers, in this case you could register for the `submit` event using jQuery for the three forms in order to intercept the event when a form is about to be submitted to the server and then append the selected value of the dropdown to either a hidden field inside the form or to the action url as query string parameter. I would probably use a hidden field. This way you will be able to retrieve the selected value in the controller action that each form is posting to.
Darin Dimitrov
+1  A: 

If the control in not inside the form tag you will not get its value in controller. The workaround could be.

1) Create a hidden field inside form

2) OnChange event of your dropdown assign the selected value to the hidden field

Edit

<%=Html.DropDownList("ProductTemplate",new SelectList(Model.ProductTemplate,"Value","Text"),new {@onchange="setVal()"})%>
.
.
<form>
.
.
<input type="hidden" id="myval" name="myval"/>
.
.
</form>
<script type="text/javascript">
function setVal()
{
$("#myval").val($("#ProductTemplate").val());
}
</script>

now in your controller you can get the value as collection["myval"]

ajay_whiz
Thanks ajay, please could provide any sample code for me thanks
@rockers please see the edit
ajay_whiz