Mich
Mich

Reputation: 151

How do I bind a MVC 5 list to a JSON object

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

Answers (4)

AlanMorton2.0
AlanMorton2.0

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

haim770
haim770

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

Tolga Evcimen
Tolga Evcimen

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

havardhu
havardhu

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

Related Questions