Shawn
Shawn

Reputation: 889

Knockout Drop Downs Populated via ASP.NET MVC Server Code

So I am new to knockout and I was searching the web unable to find a straight answer. Here is the situation. I have a dropdown list in an asp.net mvc partial view. It is populated via a viewmodel that has the values and an @Html helper, specifically dropdownlistfor. The examples I see on the web appear to require a dependent observable array, but all the values for the drop down are set in the javascript (hardcoded)/instead of via server side code. I simply want to make a span observe the output of a drop down list when the selected value changes (ie: for a live preview type functionality). Any help would be much appreciated as I am sure I'm missing something simple. Thanks!

Upvotes: 1

Views: 373

Answers (1)

mrpotocnik
mrpotocnik

Reputation: 1141

Something like this?

<select data-bind="event: {change: mySelectChange},value:myValue">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
<span data-bind="text:myText"></span>


<script>...

function ViewModel()
{
    var self = this;
    this.myValue = ko.observable();
    this.myText = ko.observable();

    this.mySelectChange = function (obj, evt) {
        var item = $(evt.currentTarget);
        self.myText(item.find('option:selected').text());
    };
}

...
</script>

Upvotes: 1

Related Questions