Search code examples
jqueryasp.net-mvc-4knockout.jsknockout-mvc

KO.Utils.PostJSon returns Null in Controller MVC 4


i am trying to create a Grid using knockout.js by following http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/

when i try to post the values from the viwe to controller always i am getting a count=0 value.But whe i try to check whether the data has the view model using alert.it comes as expected.Is there anyone faced/Fixed this issue.kindly highlight me where the error is.

her is my model.

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

Code in COntroller :

         public ActionResult Index()
    {
        var initialState = new[] {
    new GiftModel { Title = "Head First C#", Price = "49.95" },
    new GiftModel { Title = "Head First Js", Price = "78.25" }
        };
        return View(initialState);
    }

    [HttpPost]
    public ActionResult Index(IEnumerable<GiftModel> gifts)
    {
        return View();
    }

Here is what ia ma doing in view.

var initialData = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));

var viewModel = { 
    gifts : ko.observableArray(initialData), 

    addGift: function () { 
        this.gifts.push({ Title: "", Price: "" }); 
    },

    removeGift: function (gift) { 
        this.gifts.remove(gift); 
    },

    save: function() { 
        var data = ko.toJSON(this.gifts);
        alert(data);
        ko.utils.postJson(location.href, { gifts: data });
    }
}; 

ko.applyBindings(viewModel,document.body);

I have tried with normal Ajax post also.but still i am getting the same thing.

Edit: here is waht i am getting in the Alert

[{"Title":"Head First C#","Price":"49.95"},{"Title":"Head First Js","Price":"78.25"}]

Update : if i pass the pop up content directly controller can able to identify the data.

        var model = [{"Title":"Head First C#","Price":"49.95"},{"Title":"Head First Js","Price":"78.25"}];"Status": "Reserved" }];
        $.ajax({
            url: '/Grid/Index',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (result) {

            }
        });

Solution

  • Finally, i achieved it .

    We need to call ko.toJS(this.gifts) before sending the data to the request.

    Here is the Working Code.

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

    var viewModel = { 
        gifts : ko.observableArray(initialData), 
    
        addGift: function () { 
            this.gifts.push({ Title: "", Price: "" }); 
        },
    
        removeGift: function (gift) {
            this.gifts.remove(gift);
        },
    
        Save : function () {
    
            var ViewModel = ko.toJS(this.gifts);
    
    
            $.ajax({
                type: "POST",
                url: "/Grid/Index",
                data: ko.toJSON(ViewModel),
                contentType: 'application/json',
                async: true,
                complete: function () {
                    alert('success');
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert('Error');
                }
            });
        }
    }; 
    

    Thanks Ivan.Srb,szpic.