1

When I click the button 'Save' nothing happens and breakpoint in SaveProducts controller does not respond. Why? I know that it's need to implement jsondeserealize because product should be null.

HomeController.cs

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult SaveProducts(ProductModel product)
    {
        return View("Index");
    }

}

Index.cshtml

@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/knockout-2.2.0.js"></script>
<h2>Index</h2>
<div data-bind="with: currentProduct">
<p>Name: <input type="text" data-bind="value: productName" /></p>
</div>
<input type="button" value="Save" data-bind="click: saveProduct" />

<script>

function ProductViewModel() {
    var self = this;
    self.currentProduct = ko.observable(new Product("P1"));
    self.saveProduct = function () {
        var productModel = ko.toJS(self.currentProduct);
        ko.utils.postJson("/Home/SaveProducts", {product: productModel} );
    }
}
function Product(name) {
    var self = this;
    self.productName = ko.observable(name);
}
ko.observable(new ProductViewModel());

</script>

ProductModel.cs

public class ProductModel
{
    public string productName { get; set; }
}
1
  • Accepted answer looks good, but just a tip for the future; when you run into issues like this use the browser dev tools (F12) and watch the network tab and console. If you click your button and see no POST occurring, you know for sure the problem is your client-side script. Commented Feb 17, 2016 at 1:07

1 Answer 1

2

I cant see in your code where you activated your bindings and i think in this part you mean to activate it and not to create an observable.

ko.observable(new ProductViewModel());

You should change it to:

ko.applyBindings(new ProductViewModel());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.