简体   繁体   中英

How can I use knockout.js to bind data in my C# code behind to a select element on the front-end?

Here is the part of the UI that I'm trying to update:

<label>Country</label>
<select name="country" data-bind="options: $parent.CountryList, optionsCaption: '- Select -'"></select>

As you can see, I tried $parent.CountryList because I was hoping that would refer to the CountryList in the code behind. Here is a snippet of the Page_Load function where I'm storing data from a database into a list of countries:

using (CCGEntities db = new CCGEntities())
{
   List<Country> CountryList = db.Countries.ToList();
}

The goal is to take the list of countries and have them populate the select element as a dropdown menu. I tried mimicking the binding for asp:DropDownList but the code behind didn't pick up on an ID attribute for the select element. Would I be better of doing this with asp:DropDownList ?

That is not how you must do it in ASP.NET. You must create ViewModels and bind them using ko.applybindings(viewModel, YOUR_HTML_ELEMENT_ROOT) . In order to do that, the model should either:

a) Be serialized at run time by the server and dumped into a javascript variable

or b) Fetched dynamically with javascript and then apply the binding

A complete example of how to achieve this with Entity Framework, ASP.NET and Knockout is available here .

Dropdownlist population with knockout.js can seem a bit tricky at first. I ve implemented a knockout binder to make this easier:

ko.extenders.autoOptions = function (target, type) {
    target["Options"] = [];
    console.log("getting options for type: " + type);
    target.Options = ApplicationGateway.getOptions([ApplicationName.Api.Options]+type);
    return target;
};

This binder can be used in the following manner in your javascript models:

self.Gender = ko.observable().extend({ autoOptions: 'GENDER', required: { message: 'Gender is required' } });

Which results in the following template usage:

<select data-bind="options: Gender.Options,
     value: Gender,optionsText: 'Text',optionsValue: 'Value'">
</select>

My Asp.Net Web API Options Controller looks like this:

public class OptionsController : ApiController
{
    private ResourceManager _resourceManager;
    private CultureInfo _cultureInfo;

    [HttpGet]
    [Route("api/Options/{type}")]
    public List<ListItem> List(string type)
    {
        _resourceManager = new ResourceManager("Application.Resources.RESOURCE", typeof(APPLICATION).Assembly);
        _cultureInfo = new CultureInfo(Application.CurrentSession.User.LanguageSelected);

        switch (type.ToUpper())
        {
            case "GENDER": return Gender();
            ...
        }
        return new List<ListItem>();
    }

    private List<ListItem> Gender()
    {

        var items = new List<ListItem>
        {
            new ListItem(_resourceManager.GetString("Label_Gender_Male", _cultureInfo),Domain.Enums.Gender.Male.ToString()),
            new ListItem(_resourceManager.GetString("Label_Gender_Female", _cultureInfo), Domain.Enums.Gender.Female.ToString()),
        };

        return items;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM