开发者

How do I need to get My dropdownlist box value to the controller using asp.net mvc

开发者 https://www.devze.com 2023-01-12 15:57 出处:网络
Hi I have this code in my view.. &开发者_开发百科lt;%=Html.DropDownList(\"ProductTemplate\",new SelectList(Model.ProductTemplate,\"Value\",\"Text\"))%>

Hi I have this code in my view..

&开发者_开发百科lt;%=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


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 });
}


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"]

0

精彩评论

暂无评论...
验证码 换一张
取 消