开发者

Fill a drop down list based on selection in another drop down list

I am working on a website in ASP .NET MVC 3 using Razor and C#.

I have two drop down lists on a view - one for Device Type and one for Device Model. The contents for the Device Model drop down list are based off the Device Type selected. Also the Device Model drop down should be disabled until a Device Type has been selected. I would prefer the functionality to be client side.

How can I achieve this?

EDIT: Received answer in a different question: 开发者_如何学编程Fill a drop down list dynamically using Javascript/jQuery


Why not place the 2nd dd list in a container div, use Ajax to post the selected value from the first list to a controller action (onchange) that returns the rendered partial as HTML to the client and then replaces the HTML of the 2nd list's container with the action result.

If you're open to using jquery look into $.ajax and replaceWith to speak with your controller action and to dynamically rewrite your target div html respectively.


If there aren't many combinations, then you can also simply bring the entire dictionary down to the client in a JavaScript variable and then just do the whole thing client-side as you desired.

Example:

in the Controller, you would store the dictionary in the ViewBag like so:

// Keep in mind that I don't know your data structure, but you'll get the point.
ViewBag.DeviceDictionary = myDictionary;

Then in the view, you would do something like this:

<script type="text/javascript">

// new-up an array in JavaScript.
var devices = [];

// ... IT'S RAZOR TIME!!!
@foreach (Device d in ViewBag.DeviceDictionary)
{
    <text>
        // We're back in JavaScript here... new up the dictionary.
        devices[@d.ID] = [];
    </text>

    foreach (var model in d.Models
    {
        <text>devices[@d.ID].push("@model.Name");</text>
    }
}

</script>

Then, you just write some simple JavaScript (using jQuery?) that clears out the second drop down list and populates it from this array (which is client side).

Keep in mind I'm giving you an example completely making up your data-structures... but you should get the idea from this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜