Lars Holdgaard
Lars Holdgaard

Reputation: 9986

Update label depending on selected value on dropdownlist with knockout

In ASP.NET MVC, I have a form. In this form the user selects a country, and then the ID is posted back to the server, using a normal @using(Html.BeginForm) .

However, for some UX reasons, I use Knockout. Therefore I need to get my observable value countryId to have the value of a dropdownlist.

I want my label in the markup, to show the countryId, depending on the selected value on the dropdownlist.

Markup:

@Html.DropDownListFor(model => model.SelectedCountry, Model.Countries, new Dictionary<string, object> { { "class", "form-control sendaletter_countrylist" }, { "data-bind", "value:countryId" }})

<label data-bind="text: countryId"></label>

ViewModel:

 public class CreateSingleLetterModel
    {
        public CreateSingleLetterModel()
        {
            this.Countries = new List<SelectListItem>();
        }

        public string SelectedCountry { get; set; } // expected to be the ID of the SelectListItem
        public List<SelectListItem> Countries { get; set; }
 }

Then my question is:

How do I modify my DropDownListFor, so the countryId is being set automatically? :-)

Thanks a lot! I really enjoy learning Knockout, but this one has taken me a long time!

Upvotes: 0

Views: 137

Answers (1)

tabalin
tabalin

Reputation: 2313

All you've done looks correct. Now you need to define the client-side view model (where countryId will be ko.observable) and call ko.applyBindings

var viewModel = {
    countryId: ko.observable(0)
};

ko.applyBindings(viewModel);

example: http://jsfiddle.net/tabalinas/xJ7mm/

Upvotes: 1

Related Questions