简体   繁体   中英

Posting to ASP.NET MVC Controller from Knockout

I'm trying to understand knockout.js. Currently, I'm trying to do a POST to an MVC controller where my JSON object gets to the controller. Does anybody know of a downloadable code sample online? I can't seem to find any code that demonstrates this. I've seen it in the video shown here: http://channel9.msdn.com/Events/MIX/MIX11/FRM08 . However, I my approach is currently giving me a 404. I suspect it has to do with how I'm serializing something. Because of this, I'm seeking an example.

Thank you!

There is really nothing special about knockout for doing this task, other than using the ko.mapping plugin to first unwrap your model.

In this snippet, I am posting the object searchParams to Search/ExecuteSearch. This uses jQuery,

    var jsonString = ko.mapping.toJSON(this.searchParams);
    $.ajax({
        url: "/Search/ExecuteSearch",
        data: jsonString,
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        success: this.setSearchResults.bind(this)
    });

This is the controller action:

    /// <summary>
    /// Execute a search
    /// </summary>
    /// <param name="search"></param>
    /// <returns></returns>
    [HttpPost]
    public JsonResult ExecuteSearch(AdvertisementSearch search)
    {
        var searchExecutor = new SearchExecutor();
        return Json(searchExecutor.ExecuteSearch(search, CustomerData));
    }

The important thing here is that your JS Model has to have the same property names as the .NET object your MVC controller action expects, otherwise MVC model binding won't work. A design pattern I like is to manage my JS model as .NET POCO objects and then serialize an empty, default version of them to the client. This means I don't have to worry about keeping a JS file and my .NET CLR objects in synch.

I should also mention that I am using MVC 3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM