1

I am having two dropdown (PrimarySpeciality,PrimarySubSpeciality), based on the value in one dropdown(PrimarySpeciality) the other dropdown(PrimarySubSpeciality) value should change.

On Load, I want the 'PrimarySubSpecialities' on load to default value.

How can i do it?

my cshtml:

 <div class="nmc-righttab" style="width:265px;">
  @Html.DropDownListFor(m => m.User.PSpecialty, Model.PSpecialties, new { id = "ddUserDetails", style = "width:245px;height:25px;",  data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
      </div>
 <div  style="width:265px;">
    @Html.DropDownListFor(m => m.User.PSubSpecialty,Model.PSubspecialties, new { id = "ddUserDetailsPSubSpeciality", style = "width:245px;height:25px;",  data_bind = "options: pSubSpecialities,optionsText: 'Name',optionsValue: 'Id',value:PSubspecialty,enable:isPSpecialitySelected" })
   </div>

My JS File:

    this.PSubspecialty = ko.observable($('#ddUserDetails').val());
    this.pSubSpecialities = ko.observableArray([]);
    this.isPSpecialitySelected = ko.observable(false);

    this.pSpecilaityChanged = function () {

        var pSpecialityVal = $("#ddUserDetails").val();
        if (pSpecialityVal) {
            model.isPSpecialitySelected(true);
            pStartIndex = 0;
            pSubSpecialityUrl = '/User/GetSpec?pSpeciality=' + pSpecialityVal +'&sSpeciality=';
            loadPSubSpecilaities();
        }
        else
        {
            model.isSelected(false);
        }
    };

On Load,I want to set initial value for 'pSubSpeciality' to be text as '<>' with value as '0'.

Even I am able to add item to Model.PSubSpecialties,but could not be able to display the added item in psubspeciality dropdown.

How can set the initial value to pSubSpecialityDropdown from Model.PSubSpecialities.

AMDI
  • 895
  • 2
  • 17
  • 40

1 Answers1

0

Work within your model more, and with the UI less. Instead of making a changed event on the DropDownList items, subscribe to changes on a value-bound variable. In your PrimarySpecialty DropDown,

data_bind = "value: primarySpecialty"

Then in your JS:

var self = this;    
this.primarySpecialty = ko.observable();
this.isPrimarySpecialtySelected = ko.pureComputed(function () {
    return !!self.primarySpecialty();
});
this.primarySubSpeciality = ko.observable();
//...
this.primarySpecialty.subscribe(function (newValue) {
    if (newValue) {
        loadPrimarySubSpecialities();
        this.primarySubSpeciality('0'); // Set default, by value
    }
});

If the PrimarySubSpeciality dropdown has an option whose Id member is '0', the item will be selected in it.

Roy J
  • 42,522
  • 10
  • 78
  • 102