Question

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) {

            }
        });
Was it helpful?

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.

OTHER TIPS

Try to use ko.toJS instead of ko.toJSON.

Update:
Try this (instead of ko.utils.postJson):

$.ajax({
        url: <your_url>,
        type: 'POST',
        contentType: "application/json",
        data: JSON.stringify(data)
    });

I Just want to ask: You have model:

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

co why you are pushing into Price strings while it is double?

new GiftModel {/**/, Price = "78.25" }

in the link you provided this line looks:

new GiftModel { /**/, Price = 78.25 }

I'm not saying that will help solve your problem. I'm just curious.

@Update

On the this webpage: KnockOutJS Homepage You can find this line:

// To actually transmit to server as a regular form post, write this: 
ko.utils.postJson($("form")[0], self.gifts);

Without any use of ko.toJSON(data); So in you case this will be:

ko.utils.postJson(youradress,this.gifts)

check this :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top