Reputation: 151
I have a list on my model
public SelectList listItems { get; set; }
I then select the items using linq to sql
var TypeDDL = TypeMethod();
private Type[] TypeMethod()
{
var TypeDDL = (from c in db.TypeLists select new Type { Type = c.Type, cid = c.ID }).ToArray();
return TypeDDL;
}
I then set this to a viewbag item
ViewBag.TypeDDL = new List<Type>(TypeDDL);
return View(m);
What I need to know is now how do I bind this to a Json object so that i can set it to a dropdownlist using knockoutjs
thanks mike
Upvotes: 1
Views: 1881
Reputation: 1053
best way to do this is by using the html.raw helper and asigning your viewbag item to a object
var TypeList = Html.Raw(JsonConvert.SerializeObject(ViewBag.TypeDDL));
and then in JavaScript
<script type="text/javascript">
$(document).ready(function ()
{
var vm = new ViewModel();
vm.Type = ko.mapping.fromJS(@TypeList);
ko.applyBindings(vm);
});
</script>
please be aware iv used jQuery dom ready on this example
your then going to want to use a @html.DropDownList
in your razor view:
@Html.DropDownList("Typelist", (SelectList)Model.listItems, new {
id = "id",
data_bind = " options: Type, optionsText: 'Type', optionsValue: 'id'"
})
this will bind the list with knockout.js
Thanks
Upvotes: 1
Reputation: 49095
You need to serialize ViewBag.clubTypeDDL
to JSON:
<script>
var ClubTypes = @Html.Raw(Json.Encode(ViewBag.clubTypeDDL));
</script>
Then bind your drop-down element's options
to it:
<select data-bind="options: ClubTypes"></select>
Upvotes: 0
Reputation: 7352
What I usually do is I serialize the object in my controller first.
ViewBag.clubTypeDDL = JsonConvert.Serialize(new List<Type>(TypeDDL));
Then put it in a hidden input field on the view:
<input id="TypeDDL" value="@ViewBag.clubTypeDDL "/>
Then with a script:
<script>
var json = $("#TypeDDL").val(); /// here is your json string
// use this wherever you need
</script>
Upvotes: 0
Reputation: 3616
You don't need to involve a view in order to achieve this.
Rather, create a method on your controller that returns a JSON result
public ActionResult YourEndpointName()
{
var list = TypeMethod();
return Json(list, JsonRequestBehavior.AllowGet);
}
This should create a json response which you can use to populate your ko viewmodel
Upvotes: 0