I have a ViewModel into my application like this:
public class ItemViewModel {
public string Name { get; set; }
public string SelectedType { get; set; }
public IEnumerable<Type> Types { get; set; }
public string SelectedSubtype { get; set; }
public IEnumerable<Subtype> Subtypes { get; set; }
}
I’ve created a View to exposes these properties:
@Html.TextBoxFor(m => m.Name)
@Html.DropDownListFor(m => m.SelectedType,
new SelectList(Model.Types, "ID", "Description"),
"Select a type")
@Html.DropDownListFor(m => m.SelectedSubtype,
new SelectList(Model.Subtypes, "ID", "Description"),
"Select a subtype")
Well, when I want to refresh my subtypes dropdownlist, I have to write a lot of DOM code to generate the new options.
$('#SelectedType').change(function() {
$.get('/json/GetSubtypesFromType', { 'type': $(this).val() }, function(result) {
var options = '';
for (var count = 0; count < result.length; count++) {
options += "<option value='" + result[count].ID + "'>" + result[count].Description + "</option>";
}
$('#SelectedSubtype').html(options);
});
});
Is there a way to bind the new options to Subtypes enumerable into my ViewModel instead write this code for generate the options. I need to retrieve the new enumerable when I post my form, but I want to bind the new values into ViewModel collection.
Observation: You are ‘get’-ting values with AJAX and want the new values added to your DropDownList Helper.
Suggestion1: Create a custom Ajax Drop Down List Helper.
read this article on http://www.codeproject.com/Articles/421640/Creating-a-custom-AJAX-Helper
another good ref How to make the equivalent of @Ajax.DropDownList?
particularly valuable ref
http://www.mikeyd.com.au/2009/08/22/dynamically-populate-a-selectdrop-down-list-using-aspnet-mvc-jquery-and-json/
Suggestion 2: Use an action partial to create your dropdownlist
Executed as
@Html.Action("{Action}", {Controller}", new { id = {param})or from jquery as
$('#dropdowndiv').load('/{Controller}/{Action}'), action partials first call an action method, then render a partial view. This is ideal for cases where you want to dynamically create a selectlist on the fly