views:

157

answers:

3

I'm fairly new to ASP.Net MVC 2 and understand the MVC pattern in itself. But my question is what's the best way to populate dropdownlists in the UI sticking to the MVC pattern. Should I be going through the controller?

Every article I've seen to do this shows how to do it using javascript and jquery. I have a test application that I'm re-writing in MVC2 I have my dropdowns working with jquery basically calling a WCF Data Service that returns JSON which populates the dropdowns. Seems to me though that this is bypassing the controller and going straight to the model therefore strictly violating the MVC pattern.

Or am I missing something obvious here. You thoughts or best practices would be greatly welcome here.

Thanks

A: 

If your drop-down list is static (i.e. not a cascading drop-down list) then you can add an AvailableItems property to your model, set its value in your controller, and populate the list from that. If your list needs to be updated based on other user selections then you need to call back to an AJAX service of some type.

In general, if your application has script code that runs on the client, that code is going to be in your views. I personally don't see that as a violation of MVC.

John Bledsoe
A: 

I think your best bet is to give View Models a try.

You can build fill out data for special UI oriented models in the controller and pass that to the view. For drop downs, is there a reason you're loading through ajax? In most cases I've found you can just build a normal select list and sprinkle with javascript for dynamical functionality.

Your view model could have a IEnumerable<String> CityNames property that you then load into a dropdown in the view.

Jason
+3  A: 

One of the great things about MVC is that the controllers can couple as 'web services' or sort. Meaning, you can easily specify a return type of 'JsonResult' for example (instead of a view - ActionResult).

The MVC framework will handle all the serialization for you.

You can easily call the controller action method from jQuery and populate the dropdown.

In your example, i would create a Json controller method, decorate it with some custom action filters (check http headers that its a json http get request, etc), call it from jQuery and bind to your dropdown.

RPM1984
This is how I do it. The only change I would make is that the JSON calls should be POST, http://haacked.com/archive/2009/06/25/json-hijacking.aspx
Alastair Pitts
Agree (for security purposes)
RPM1984