How to Bind Static Data Using Knockout in MVC

410 views Asked by At

I am Using Knockout With MVC for the first time. I am trying to show the Name and Surname which will be static and will be shown as they are defined in the Controller Class. I had tried my level best to show the Data but it's Output is not as I had expected. My Code is as Follows: Model Class

using PerpetuumSoft.Knockout;
using PerpetuumSoft;
using DelegateDecompiler;

namespace MvcApplication20.Models
{
 public class Class1
{

    public string Number { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }

 }
}

This is my Controller Class

using System.Web.Mvc;
using MvcApplication20.Models;
using PerpetuumSoft.Knockout;

namespace MvcApplication20.Controllers
{
 public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    { 
        Class1 student = new Class1();
        student.Number = "B123456";
        student.Name = "Anubhav";
        student.Surname = "Chaudhary";
        return View(student);
    }

 }
}

This one is my Index Class

@using System.Web.Script.Serialization;
@model MvcApplication20.Models.Class1   

<h2>Indexer</h2>
<script src="~/Scripts/knockout-2.1.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<p> Name:<span data-bind="text:Name"></span></p>
<p> SurName:<span data-bind="text:Surname"></span></p>
<script type="text/javascript">
  $(function()
 {

     var model = @Html.Raw(Json.Encode(Model))         
        ko.applyBindings(model);
  });
  </script>

My Output is like this:

Name:

Surname:

As you can see it's not showing the Name which I had provided in the coding Section, please help me out and tell me what to do so that I can get the desired output.

3

There are 3 answers

1
Rustam On

Can you confirm that all scripts are loaded? I think this is not correct path (based on the statndard MVC folder locations)

'<script src="~/Scripts/knockout-2.1.0.js"></script>'

and this one is might be correct:

'<script src="@Url.Content("~/Scripts/knockout-2.1.0.js")"></script>'
1
Siyamand On

Your ViewModel properties are not knockout observable properties. You can useknockout mapping plugin . In this case your javascript must be:

$(function()
{
 var model = @Html.Raw(Json.Encode(Model))  
 var viewModel = ko.mapping.fromJS(data);
 ko.applyBindings(viewModel );
});    
0
Kate Fernando On

H,

This is an old post.I answered this because if someone has this issue , my solution will work for them too.

You have to add jquery plugin before the knockout.js plugins.

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script src="~/Scripts/knockout-2.1.0.js"></script>

<script src="~/Scripts/knockout.mapping-latest.js"></script>