开发者

Dynamically updating html.listBox in MVC 1.0?

The client will choose an item from a dropDown list, this newly selected value will then be used to find assets linked to that selected item, these assets will then be loaded into the listBox.

This sounds simple enough, and I'm aware I could use a partial View but it seems overkill for just updating one com开发者_C百科ponent on a form.

Any


I've done this in MVC 1.0 myself. I used an onchange on the first drop down which called an action using the value selected. That action returned a JSON result. The jQuery script which called that action then used the JSON to fill the second drop down list.

Is that enough explanation, or would you like help writing the javascript, the action, or both?

Inside your view:

<%= this.Select("DDLName").Attr("onchange", "NameOfJavascriptFunction();") %>
<%= this.MultiSelect("ListBoxName") %>

The javascript will look like this:

function NameOfJavascriptFunction() {
    var ddlValue = $("DDLName").val();
    jQuery.ajax({
        type: 'GET',
        datatype: 'json',
        url: '/Controller/Action/' + dValue,
        success: updateMultiSelect
    });
}

function updateMultiSelect(data, status) {
    $("#ListBoxName").html("");
    for(var d in data) {
        $("<option value=\"" + data[d].Value + "\">" + data[d].Name + "</option>">).appendTo("#ListBoxName");
    }
}

Finally, the action is something like this (put this in the controller and action from the first javascript):

public ActionResult Action(int id) //use string if the value of your ddl is not an integer
{
    var data = new List<object>();
    var result = new JsonResult();
    this.SomeLogic.ReturnAnEnumerable(id).ToList().ForEach(foo => data.Add(new { Value = foo.ValueProperty, Name = foo.NameProperty }));
    result.Data = data;
    return result;
}

Feel free to ask follow up questions if you need any more explanation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜