loki
loki

Reputation: 2966

How to use knockout.js in MVC 3 Razor?

i am newbie knockout.js. Also i ama upper intermadiate in asp.net mvc 3. i really want to learn how to use knockout js in mvc 3 razor? but below code is not working also return to me empty total price. There is no error. Help please thanks...

Model:


  public class GiftModel
    {
        public string Title { get; set; }
        public double Price { get; set; }
    }

View:


@using System.Web.Script.Serialization;
@model IEnumerable<knockout1.Models.GiftModel>
@{
    ViewBag.Title = "Index";
}

<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script type="text/javascript">
    var initialData = @(new JavaScriptSerializer().Serialize(Model));
    var viewModel = {
    gifts : ko.observableArray(initialData)
};

ko.applyBindings(viewModel);
</script>
<h2>Index</h2>

<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>

Controller:


   public class TestController : Controller
    {
        //
        // GET: /Test/

        public ActionResult Index()
        {
            var initialState = new[] {
                                     new GiftModel { Title = "Tall Hat", Price = 49.95 },
                                     new GiftModel { Title = "Long Cloak", Price = 78.25 }
                                    };
            return View(initialState);
        }

    }

Upvotes: 3

Views: 4239

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

I guess you are following this tutorial.

You have a couple of errors. First replace:

var initialData = @(new JavaScriptSerializer().Serialize(Model));

with:

var initialData = @Html.Raw(Json.Encode(Model));

This ensures that your model is properly JSON encoded. In the original article Steven Sanderson is using the WebForms view engine but you seem to be using the Razor view engine. So make sure that you adapt your syntax accordingly (don't forget that the @ razor function automatically html encodes the output contrary to the <%= WebForms syntax).

And the second problem with your code is that you attempted to bind your knockout model before your DOM is ready (i.e. you have placed the ko.applyBindings(viewModel); call before the actual span containing the bindings). So either wrap your call in a $(document).ready or place your scripts at the end of the document, just before closing your </body> tag (recommended).

Also I would recommend you using url helpers to reference your scripts, don't just hardcode those urls, your application will break as soon as you publish in IIS:

@model IEnumerable<GiftModel>

<h2>Index</h2>

<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>

<script src="@Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>
<script type="text/javascript">
    var initialData = @Html.Raw(Json.Encode(Model));
    var viewModel = {
        gifts : ko.observableArray(initialData)
    };

    ko.applyBindings(viewModel);
</script>

So as you can see the 2 problems you were having have strictly nothing to do with knockoutjs. So what I would recommend you if you want to learn some framework is to learn it independently. Don't mix up technologies or you will get mixed up.

So go ahead over the knockoutjs site and start the tutorials working on static HTML pages. Forget about ASP.NET MVC for the moment. Forget about Entity Framework. Just learn the framework starting from a static HTML page. This way you will better understand how it works.

Upvotes: 15

Related Questions