How can I use knockout.js to set the selected option in asp.net mvc?

I'm trying to default select an option based on a value received from Model using asp.net mvc and knockout js for data binding.

//Model.TestValue="DEF"

script section.

<script>
var model = {
            MyData: ko.mapping.fromJS(@Html.Raw(Json.Serialize(Model)))
        };

ko.applyBindings(model);  
</script>

View Section: Razor

@{
   var mydropdownlist = new SelectList(
        new List<SelectListItem>
        {
new SelectListItem {Text = "ABC", Value = "1"},
new SelectListItem {Text = "DEF", Value = "3"},
new SelectListItem {Text = "GHI", Value = "5"}
        }, "Value", "Text");

}

View Section HTML.

<select data-bind="options: mydropdownlist, optionsText:'text', value:MyData.testValue "></select>

Although mydropdownlist populates correctly, I am facing issue with setting "DEF" as the default selected option.

Answer №1

Assign the value of MyData.testValue to be the second item in mydropdownlist.

MyData.testValue(mydropdownlist.Items()[1]); //DEF

For instance:

$(function() {

    var VmClass = function() {
        self.MyOptions = ko.observableArray([
            { Name: 'Jhon', Age: 45 }, { Name: "Peter", Age: 67 }, { Name: 'Oliver', Age: 90}
        ]);

        self.SelectedOption = ko.observable();

        // Can be selected after binding initialized too.
        self.ClickMeToSelect = function() {
            self.SelectedOption(self.MyOptions()[2]);
        };
        self.ClickMeToSelect();
    };

    var vmInstance = new VmClass();
    ko.applyBindings(vmInstance, document.getElementById('[element-id]')); 
});

Answer №2

Do you think this is the solution you are looking for?

var items = [
  {"name": "Apple","quantity": 10},
  {"name": "Banana","quantity": 20},
  {"name": "Cherry","quantity": 30},
  {"name": "Date","quantity": 40},
];

var inventory = {
  itemList: ko.observableArray(items),
  selectedProduct: ko.observable(items[1])
};

ko.applyBindings(inventory);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select data-bind="options: itemList, optionsText:'name', value:selectedProduct "></select>

<pre data-bind="text: ko.toJSON($root.selectedProduct)"> </pre>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS Flexibility

Greetings everyone, it's been a while since I dabbled in web development. I recently worked on my site with the intention of making it responsive using flexbox. This is my first time posting here, so please guide me on how to seek help more effective ...

Utilize the connect-multiparty middleware to retrieve files from an undefined request

Attempting to upload image files to the server using connect-multiparty router.post('/image', multipartMiddleware , function(req, res) { console.log(req.body, req.file); }); <form method="post" action="/products/image"> <input ty ...

Transferring information between different collections in MongoDB using Mongoose can lead to encountering a VersionError

I'm facing an issue where Mongoose is unable to find a matching document with the id when transferring data from one collection to another. On my website, users search for classes in a Mongo DB collection called "classes." Once they find a class succ ...

What is the best way to showcase one object per day when I have an array of 30 objects in Ionic 4?

I'm looking to showcase a different quote in my app every day for 30 days using an array of 30 quotes. How can I achieve this daily quote rotation in Ionic 4? ...

Is it possible to reach this result without relying on Modernizr?

Due to personal reasons that I won't delve into, my goal is to replicate the functionality of this menu : demo : http://tympanus.net/codrops/2013/04/19/responsive-multi-level-menu/ However, I want to achieve this without using Modernizr and poss ...

When I click the search button on my website, it automatically scrolls to a particular <img> or <a> tag

My objective is to have the page automatically scroll down to a specific image when I perform a search using the search bar. Here is the HTML code for the search bar and button: <form id="search-form" href="#test1" class="smoothscroll"> <inpu ...

Retrieve the data from an HTTP Request using AngularJS

I've been working on creating a JavaScript function that sends an HTTP Request to retrieve data, but I'm struggling with how to handle and use the result in another function. Here are the two functions I've tried (both intended to achieve t ...

JavaScript Datepicker Formatting

I need to modify the date format of a datepicker. Currently, it displays dates in MM/DD/YYYY format but I want them to be in DD-MM-YYYY format. <input id="single-date-picker" type="text" class="form-control"> Here's the JavaScript code: $("# ...

Retrieve data points from ol.layer.Vector using OpenLayers 4

Having recently started using OpenLayers, I find myself in a state of confusion. I'm attempting to retrieve all features from a kml vector layer, but have been unsuccessful thus far. It perplexes me as to what mistake I might be making. Below is the ...

Mix up the colors randomly

After searching extensively, I have been unable to find exactly what I am looking for. The closest matches only cover a portion of my needs which include: I am seeking a randomly selected color scheme that I have created but not yet implemented in code. T ...

The function data() is coming back as null

This is the code snippet I am working with: $.getJSON("link here", function (result) { $.each(result, function (i, value) { $('.usersOfGroupList').append($("<li id='userElement' data-userId='' ></li>") ...

Tips on crafting tailored CSS styling for targeted div elements such as before and after:

Looking to style specific div elements with the same class name? <div class="main"> <div class="banner_image"> banner 1</div> <div class="banner_image ">banner 2</div> <div class="banner_image ">banner 3</di ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

Trouble is arising in rendering events with years before 100 (specifically years 0000 - 0099) when using the ISO8601 format in fullCalendar

I've created a Calendar that showcases various events using fullcalendar. The events span from the years 0001 to 6000. Fullcalendar requires dates in ISO8601 format, and I am providing them as such. Events from the years 0100-6000 render perfectly w ...

Issue with Mat-AutoComplete arising while utilizing a formArray

After adding a form array to account for multiple rows, I had to modify my definition from: shoppingCartList Observable<any[]>; to shoppingCartList: Observable<any[]>[] = [];. However, this change resulted in an error in my filter function whic ...

What is the best way to add information stored in localStorage to an element on the webpage?

At the moment, I am developing a Bookmark manager that stores data in localstorage and then adds the saved data from localstorage to the DOM. However, I am facing an issue where the code inside fetchUrl() is not getting appended to the DOM. Here is what I ...

How can I conduct AngularJS debugging within Chrome's developer tools?

I am currently troubleshooting a $http issue in our application. When I step into $http.get, the debugger does not display the values of any AngularJS local variables. Hovering over them shows nothing and right-clicking 'Evaluate in console' thro ...

How can you use the MongoDB Aggregation Framework to filter by a range of dates, group results by individual days, and calculate the average value for each day

I'm currently exploring the possibilities of MongoDB's Aggregation Framework and would appreciate some assistance in enhancing this query to achieve the following objectives: Retrieve Records with Dates falling within a specified range Organize ...

The angular 5 application encountered an issue where it was unable to access the property 'singlePost' due to a null value, resulting

When using the once method to fetch data from the Firebase database, everything works correctly. However, when I try to use the on method, I encounter an error that says: ERROR TypeError: Cannot read property 'singlePost' of null. How can I prope ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...