Skip to content Skip to sidebar Skip to footer

How To Bind Data From Razor To Knockout?

I am using KnockOut JS and MVC. How do I bind the data from @ RAZOR view to my databind in KO. I tried doing this but did not return anything at the CONTROLLER. What I am trying to

Solution 1:

You're creating a single element observable array by calling the RowData constructor, but you're not passing any parameters in.

self.ApprTable = ko.observableArray([new RowData()]);

The function definition requires a lot of parameters

function RowData(Appropriation, PriorityDate, Location, Source, Owner, Use, StartedBy, RequiredReporting)

You're not actually putting any data into the observables.


Solution 2:

You are mixing the stuff. If you want to init the view from razor data, you can do it in two ways:

First, generate JSON in the controller and load it to knockout view model using "knockout-mapping" plugin, for example your view may contain:

<script>
    $(function () {
        ko.mapping.fromJS(@Html.Raw(ViewBag.jmodel), null, viewModel);
    });
</script>

of course you should prepare ViewBag.jmodel in your controller, like this:

JsonSerializer js = JsonSerializer.Create(new JsonSerializerSettings());
var jw = new StringWriter();
js.Serialize(jw, <your object here>);
ViewBag.jmodel = jw.ToString();

Other way is to generate code that will add data row by row like you attempted to do:

var viewModel=new Step3ViewModel();
ko.applyBindings(viewModel);

@for (int i = 0; i < UserWRInfo.Count; i++)
{
  viewModel.ApprTable.push(new RowData(@UserWRInfo[i].AppropriationNumber, /*other values here to create full row of data row*/)
}

This way will generate as many viewModel.ApprTable.push(...) lines as you have in your data set.

And of course, your table with data and knockout binding should NOT contain any razor code!!!

<tbody data-bind="foreach:ApprTable">
...
    <td style="text-align: center" data-bind="value: Appropriation"></td>
...
</tbody>

Post a Comment for "How To Bind Data From Razor To Knockout?"