Hi all, I apologize for the long hiatus but today, I discovered something new.
My new role allows me to play with a few more cool toys, eg: WCF, MongoDB, Fluent NHibernate and MVC.
Today I am going to be touching a little bit on MVC and specifically having to deal with retaining the value after selecting a drop down list item.
Previously, in Web Forms, we have the SelectedIndexChanged function that helped us.
However, there is none of that in MVC.
Thus, to solve this, I leverage the power of jQuery.
Before I begin, this was done using MVC2.
What I did was to use the standard Html.Select control on the View and have a hidden field (Html.Hidden in MVC2). Both the hidden and select control must use the same parameter. See the example below,
Html.Hidden( x => x.Field1).Id("hiddenFieldId")
Html.Select( x => x.Field1).Options([INSERT LIST TO BIND HERE]).Selected(Model.Field1).Id("dropDownListId")
After this, I leveraged jQuery in the document.ready() function to implement the change function for the drop down list.
Place the below within the document.ready() function.
$("#dropDownListId").change(function(e) {
var value = $(this).val();
$("#hiddenFieldId").attr("value", value);
});
We can now leverage the Html.Hidden field; Field1 in our code behind.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment