在 MVC 中将值设置为 select 下拉列表的问题

Issue with setting value to select dropdown in MVC

我正在使用 MVC。

我有两个下拉菜单和 'primaryspec' 的一个更改应该加载 'primarysubspec'。

将值传递给控制器​​一切正常,它已保存到数据库中。

当我尝试检索保存的详细信息时,'primarysubspec' 保存的值没有显示。

但显示 'primarySpec' 的保存数据。

这是我的 .cshtml 代码:

 @Html.DropDownListFor(m => m.PSpec, Model.PSpec, new { id = "ddUserSpec", style = "width:245px;height:25px;",  data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)


  @Html.DropDownListFor(m => m.PSubspec, Model.PSubspec, new { id = "ddUserSubSpec", style = "width:245px;height:25px;",  data_bind = "options: primarySubSpec,optionsText: 'Name',optionsValue: 'Id'" }, Model.IsReadOnly)

这是我的 JS 代码,用于检索 :

的值
this.primarySubSpec = ko.observableArray([]);

    this.primarySpecChanged = function () {

      var val = $("#ddetailsPrimarySpec").val();
      primarySubStartIndex = 0;
      primarySubSpecialityUrl = '/PlatformUser/GetSpecandSubSpec?primarySpe=' + val+//model.primarySpecID() +'&secondarySpec=';
            loadPrimarySubSpec();
        };

function loadPrimarySubSpec() {

        $.ajax({
            type: 'GET',
            url: primarySubSpecUrl,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            processdata: false,
            cache: false,
            success: function (data) {

                primarySubSpec = [];
                model.primarySubspec('0');
                try {
                   if (data.length == 0) {
                    primarySubSpeacId.empty();
                }
                model.primarySubSpec(data);
            },
            error: function (request, status, error) {
                primarySubSpeacId.prop("disabled", true);

            }

        });
    }

一切正常,但仅在显示数据库中保存的值时遇到问题。

显示 'primarySpec' 罚款 'PrimarySubSpec' 的值显示为空,而不是下拉列表中保存的值。

请告诉我问题是什么,我如何才能将保存的值显示为“primarySubSpec”下拉列表中的选定值。

问题: 当您加载页面以查看保存的值时,永远不会调用更改事件。

为什么: 当您的页面加载了保存的值时,select 框会在 knockout 知道之前 select 保存值。未调用更改事件。

最简单的解决方案: 如下更改 primarySpecilaityChanged

this.primarySpecilaityChanged = function () {
  var val = $("#ddUserDetailsPrimarySpeciality").val();
  if(val){
    primarySubStartIndex = 0;
    primarySubSpecialityUrl = '/' + NMCApp.getVirtualDirectoryName() + '/PlatformUser/GetSpecialitiesandSubSpecilaities?primarySpeciality=' + val+//model.primarySpecialityUID() +'&secondarySpeciality=';
    loadPrimarySubSpecilaities();
  }
};

然后在调用 ko.applyBindings 之后调用 primarySpecilaityChanged 函数。

var viewModel = new YourViewModel();
ko.applyBindings(viewModel);
viewModel.primarySpecilaityChanged();