A191919
A191919

Reputation: 3442

asp.net post json to controller

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; }
}

Upvotes: 1

Views: 46

Answers (1)

Adrian
Adrian

Reputation: 1587

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());

Upvotes: 2

Related Questions