wingyip wingyip - 5 months ago 12
jQuery Question

Display dynamic items on page after initial page load

I am using ASP.Net mvc to render my html view.

The view contains a dropdown list and a label

I load drop down list using a collection in my view model.

Lets say that the collection is called fruit

IList<Fruit> fruit

Fruit is defined as


The dropdown list will display each Fruit name and have a value of FruitId

When I change the value of the drop down list I want to have the value of my label display FruitType.

I can think of a couple ways of doing this:

  1. Write out Label tags for all values of FruitType. Give a css class to display the first one on load and add javascript to show/hide labels in the select onchange event

  2. Provide json array of Fruit in the html somewhere (I would serialise the Fruit list on page load and put the resulting script on the page somewhere). I would add javascript to the onchnage event of the select to search the json and change the label value accordingly.

I have 2 questions:

  1. Am I missing something obvious, could this be done in a better way?

  2. If no 2 is a good idea, where should I put the json in the html so that the js can use it?


Another approach is that when you generate the dropdown list, include a data-attribute, say data-fruit-type where you store the FruitType, then when the dropdown value changes, just read the data-fruit-type attribute from the selected item.