Reputation: 6234
I have a SelectList
representing a delivery type for an order.
The delivery type reference data has the usual code/description, but also an additional boolean property which indicates if further information needs to be entered for the type selected.
So for Emergency deliveries additional data is required. The additional data entry fields would be set visible if Emergency was selected, otherwise hidden
My ViewModel
contains <List>ReferenceDeliveryTypes
which contains the 3 properties.
I have created a SelectListItems
from the ViewModel data
@Html.DropDownListFor(model => model.DeliveryTypeCode,
new SelectList(Model.ReferenceDeliveryTypes as System.Collections.IEnumerable,
"DeliveryTypeCode", "DeliveryTypeDescription"), new { id = "ddlDeliveryType" })
How can I call a jQuery function on change of the delivery type, pass the selected code and check the Model.ReferenceDeliveryTypes
for that code to see if the additional data property is true/false to show/hide the additional fields div
?
I have managed to get the jQuery function called to pass the value.
$(function () {
$('#ddlDeliveryType').change(function () {
var value = $(this).val();
alert(value);
});
});
Upvotes: 1
Views: 22088
Reputation: 6234
I converted the Model.ReferenceDeliveryTypes to a JSON list which allowed me to access it from the jQuery.
Possibly not the best way, but it allows me to do everything on the client rather than making an AJAX call back. I can now show/hide the inside the if block.
Thought it worth documenting what I did as I've not come across the @Html.Raw(Json.Encode
before and it might prove useful for someone who wants to access model data from within jQuery.
Any additional comments welcome.
<script type="text/javascript">
var [email protected](Json.Encode(Model.ReferenceDeliveryTypes))
</script>
@Html.DropDownListFor(model => model.DeliveryTypeCode,
new SelectList(Model.ReferenceDeliveryTypes.ReferenceDeliveryType as System.Collections.IEnumerable,
"DeliveryTypeCode", "DeliveryTypeDescription"), new { id = "ddlDeliveryType" })
$(function () {
$('#ddlDeliveryType').change(function () {
var selectedDT= $(this).val();
$.each(ReferenceDeliveryTypeJsonList, function (index, item) {
if (selectedDT === item.DeliveryTypeCode) {
alert("match " + selectedDT);
}
});
});
});
Upvotes: 1
Reputation: 5550
I don't know of any way you can do this using a select list but I suggest the following options:
Good luck
UPDATE
For the hidden field option if you use something like 123|456|789|
and then use indexOf
having appended a |
to the selected ID.
Upvotes: 1