Note that there are some explanatory texts on larger screens.

plurals
  1. POMake SelectList observable
    primarykey
    data
    text
    <p>I would like to make my SelectList observable so the ViewModel gets updated with changes made to that SelectList. I see the values displayed in the drop down list in my UI but I never see that selected value updated in my ViewModel, It is always null. I have other controls on the form that are updated without issue so I would like to know how, specifically, to make a SelectList observable. It seems SelectLists and knockout are a little different than a standard input control.</p> <p>I have the following in a class:</p> <pre><code>public string LocationId { get; set; } public IEnumerable&lt;SelectListItem&gt; Locations { get; set; } </code></pre> <p>I have the following that populates my array of locations:</p> <pre><code> private PersonViewModel _viewModel; public ActionResult Index() { var locations = new[] { new SelectListItem { Value = "US", Text = "United States" }, new SelectListItem { Value = "CA", Text = "Canada" }, new SelectListItem { Value = "MX", Text = "Mexico" }, }; _viewModel.Locations = locations; return View(_viewModel); } </code></pre> <p>I have the following in my markup:</p> <pre><code>&lt;script type="text/javascript"&gt; Person.ViewModel = ko.mapping.fromJS(@Html.Raw(Json.Encode(Model))); var locationsArray = ko.observableArray(@Html.Raw(Json.Encode(Model.Locations))); &lt;/script&gt; &lt;form&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; Locations: &lt;/td&gt; &lt;td&gt; @Html.DropDownListFor(model =&gt; model.LocationId, new SelectList(Model.Locations, "Value", "Text"), new { id = "locationsArray" }) &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload