1

I have the Drop down list which is populated from a GetJSON call as shown below

VIEW

@{
   var NoticeFilter =(X.Models.Y.Z.NoticesEntity) ViewData["NoticeFilter"];
}


<div class="form-group">
    <label>Field Office</label>
    <select  data-bind="options: FieldOffice, value: selectedFieldOffice, optionsCaption:'Choose...', optionsValue:'FieldOfficeID', optionsText:'Name'">
        @if(NoticeFilter!=null)
        {
            <option value="@NoticeFilter.FieldOfficeID" selected></option>
        }
    </select>
</div>

When I direct to this page and send data into the NoticeFilter I want the value in drop-down pre-selected with the value in Noticefilter among the other values .How do I achieve this

I was wondering if there is way in razor HTML where I can set a default value to Drop-Down after the data-binding from KO JS

sss111
  • 349
  • 1
  • 7
  • 27

2 Answers2

1

Have you tried this?

<script>
var str = @Html.Raw(Json.Encode(ViewData["Text"]));
</script>
imGreg
  • 900
  • 9
  • 24
  • I cannot use this as I am using Knockout JS in order to bind data to the drop down hence the issue. – sss111 May 19 '15 at 15:58
  • just add the data-bind into the object htmlattribute section of that razor statement. "@data_bind" is "data-bind" – imGreg May 19 '15 at 16:10
  • But is this going to work cause I dont have a model initialized for the view and Noticefilter is null most of the time. – sss111 May 19 '15 at 16:28
  • Okay ignore my current answer but how about calling the list with ajax into js then appending the options with jquery ? – imGreg May 19 '15 at 16:32
  • I tried this http://stackoverflow.com/questions/30266755/how-to-pass-viewdata-from-controller-to-my-js – sss111 May 19 '15 at 16:38
  • Here I try to send the List to JS via VIEWDATA but unable to do that – sss111 May 19 '15 at 16:39
  • look at my answer again and tell me if you tried that ? – imGreg May 19 '15 at 16:42
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/78230/discussion-between-imgreg-and-sss111). – imGreg May 19 '15 at 16:43
0

WORKING After few attempts I found this as one way to access the ViewData or ViewBag in my JS

I used the KO JS optionsAfterRender as below

VIEW

<select  data-bind="options: SubType, value: selectedSubType, optionsValue:'SubTypeID', optionsText:'SubTypeDescription',optionsAfterRender:function(){setOptionST(@Noticefilter .SubTypeID);}"></select>

JS

In the view model

 self.setOptionST = function (x) {
        //here we can do whatever is intended to in my case to set the initial value in dropdown
        self.selectedSubType(x);
    };
sss111
  • 349
  • 1
  • 7
  • 27