4

I have an observable array Object that which is generated like this:

 self.SelectedVariable = ko.observableArray();
    self.VarUpdate = function (data) {
        $.getJSON("/api/Variable/" + ko.toJS(data.VarID), ko.toJS(data.VarID), function (Result) {
            for (var i = 0; i < Result.length; i++) {
                element = Result[i];
                self.SelectedVariable({ VariableID: ko.observable(element.VariableID), VariableDateLastUpdated: ko.observable(element.VariableDateLastUpdated), VariableName: ko.observable(element.VariableName), VariableDescription: ko.observable(element.VariableDescription), VariableValue: ko.observable(element.VariableValue), VariableType: ko.observable(element.VariableType) });
            };
        });

When I try to pass the SelectedVariable object to my WebAPI method using this AJAX call

  $.ajax({
            url: "/api/Variable?Del=0",
            data: { vardata: ko.toJS(self.SelectedVariable) },
            type: "PUT",
            dataType: "JSON",
            timeout: 10000,
            success: function (Result) {

            },
            error: function (xhr, status) {
                alert(status + " - " + xhr.responseText);
            }
        });

, all the related object shows null on all the fields. enter image description here I have tried almost every combination to get the SelectedVariable Object to parse correctly to my WebAPI method:

data: { vardata: ko.toJS(self.SelectedVariable) },

data: { vardata: ko.toJSON(self.SelectedVariable) },

data: { vardata: JSON.Stringify(self.SelectedVariable) },

data: { vardata: self.SelectedVariable },

and have tried to manually decrypt JSON object on WebAPI side using:

    public void Put([FromUri] int Del, [FromBody]string vardata)
    {

        Variables vari = JsonConvert.DeserializeObject<Variables>(vardata);

        var Item = (from c in TMIRE.Variables
                    where c.VariableID == vari.VariableID
                    select c).First();

        if (Del == 0)
        {
            Item.VariableDateUpdated = DateTime.Now;
            Item.VariableName = vari.VariableName;
            Item.VariableDescription = vari.VariableDescription;
            Item.VariableValue = vari.VariableValue;
            Item.VariableType = vari.VariableType;

And It is still null value.

Any Advice would be greatly appreciated!

UPDATE

Changed my WebAPI method to reflect as follows:

 public void Put([FromUri] int Del, IEnumerable<Variables> vardata)
    {
        var Item = (from c in TMIRE.Variables
                    where c.VariableID == vardata.Select(x => x.VariableID).First()
                    select c).First();
        if (Del == 0)
        {
            Item.VariableDateUpdated = DateTime.Now;
            vardata.Select(a => Item.VariableName = a.VariableName);
            vardata.Select(b => Item.VariableDescription = b.VariableDescription);
            vardata.Select(c => Item.VariableValue = c.VariableValue);
            vardata.Select(d => Item.VariableType = d.VariableType);
        }

and now the vardata object gets the value but all objects within are null enter image description here My Ajax method looks like this:

 alert(ko.toJSON(self.SelectedVariable));
        $.ajax({
            url: "/api/Variable?Del=0",
            contenttype: "application/x-www-form-urlencoded",
            data: "=" + ko.toJSON(self.SelectedVariable()),
            type: "PUT",
            dataType: "JSON",
            timeout: 10000,
            success: function (Result) {

            },
            error: function (xhr, status) {
                alert(status + " - " + xhr.responseText);
            }
        });

The alert gives me this response

enter image description here

The Variables Class

 public class Variables
{
    public int VariableID { get; set; }
    public DateTime VarialbeDateLastUpdated { get; set; }
    public string VariableName { get; set; }
    public string VariableDescription { get; set; }
    public string VariableValue { get; set; }
    public string VariableType { get; set; }

}

Working Code

By using this Ajax call

  $.ajax({
            url: "/api/Variable?Del=0",
            contenttype: "application/x-www-form-urlencoded",
            data: "=" + ko.toJSON(self.SelectedVariable),
            type: "PUT",
            dataType: "JSON",
            timeout: 10000,
            success: function (Result) {

            },
            error: function (xhr, status) {
                alert(status + " - " + xhr.responseText);
            }
        });

and then using Newtonsoft to deserialize the object on WebAPI using this method:

public void Put([FromUri] int Del, [FromBody]string vardata)
    {

        Variables vari = JsonConvert.DeserializeObject<Variables>(vardata.Substring(1, vardata.Length-2));

        var Item = (from c in TMIRE.Variables
                    where c.VariableID == vari.VariableID
                    select c).First();

        if (Del == 0)
        {
            Item.VariableDateUpdated = DateTime.Now;
            Item.VariableName = vari.VariableName;
            Item.VariableDescription = vari.VariableDescription;
            Item.VariableValue = vari.VariableValue;
            Item.VariableType = vari.VariableType;
        }
        else
        {
            Item.VariableDateUpdated = DateTime.Now;
            Item.VariableActive = false;
        }

        TMIRE.SaveChanges();
    }

I Got it to work

3
  • before you hit the ajax call, have you used Chrome dev tools to check the values of self.SelectedVariable? Commented Jul 2, 2014 at 19:44
  • I have, and the object generates correctly on client side. I also added and alert to my Ajax call to see if the JSON generates correctly. And it does. Here is the JSON I get From Client Side { "VariableID": 4, "VariableName": "Admin EMail Address", "VariableDescription": "The Email Account for Administration Panel.", "VariableValue": "[email protected]", "VariableType": "String" } Commented Jul 2, 2014 at 19:46
  • 2
    shouldn't the WebAPI be expecting IEnumerable<Variables> vardate, since you're building a collection? Commented Jul 2, 2014 at 19:50

4 Answers 4

3

Try this...

public void Put([FromUri] int Del, IEnumerable<Variables> vardate){}

Since you're building a collection on the client self.SelectedVariable = ko.observableArray();, you will need the API to receive an IEnumerable.

In the Ajax call, I think it would be best to use:

data: { vardata: ko.toJSON(self.SelectedVariable) }

as this will give you a JSON representation of the collection.

Also, on the KO side, shouldn't you be pushing elements into the collection? self.SelectedVariable.push({...}); or you will end up with only the final result.

Sign up to request clarification or add additional context in comments.

5 Comments

Now its = 0. Changed my put method to reflect like this public void Put([FromUri] int Del, [FromBody]IEnumerable<Variables> vardata) and ajax to data: { vardata: ko.toJSON(self.SelectedVariable) },
I have added an update section to the original question
can you add the code for the class Variables just the properties?
Added to bottom of Question. Keep in mind I am using Database First methodology and Not Code first.
I made a hasty response, disregard it. You are correct.
1

Change assignment to this:

    self.SelectedVariable = ko.observableArray();
    self.VarUpdate = function (data) {
        $.getJSON("/api/Variable/" + ko.toJS(data.VarID), ko.toJS(data.VarID), function (Result) {
            var selection = self.SelectedVariable;
            for (var i = 0; i < Result.length; i++) {
                var element = Result[i];
                selection.push(element);
            };
        });

Then, Change the ajax method to convert to json:

    $.ajax({
        url: "/api/Variable?Del=0",
        content-type: "application/x-www-form-urlencoded",
        data: "=" + JSON.stringify(ko.toJSON(self.SelectedVariable)),
        type: "PUT",
        dataType: "JSON",
        timeout: 10000,
        success: function (Result) {

        },
        error: function (xhr, status) {
            alert(status + " - " + xhr.responseText);
        }
    });

Also try removing [FromBody].

public void Put([FromUri] int Del, IEnumerable<Variables> vardata)
{
    ...
}

It looks like making the serialized objects in vardata as ko.observable objects is confusing mvc serialization for the parameters.

different data assignments to attempt:

data: "=" + JSON.stringify(ko.toJSON(self.SelectedVariable))

data: "=" + JSON.stringify(self.SelectedVariable())

data: "=" + self.SelectedVariable()

data: "=" + $.parseJSON(ko.toJSON(self.SelectedVariable))

10 Comments

Changed it exactly ass suggested. vardata is still = 0
Also try adding content-type, changing assignment to data as noted in my recent edit, and removing frombody.
It Finally parsed the object, but all the values within SelectedVariable are null.
Update your original post with the values of self.SelectedVariable() in the client before $.ajax and the most up-to-date-code that you have for your mvc service. I will change my response according to your edit.
I finally got it to freaking work! See working code section Thanks for all the help. If you ever find yourself in South-Africa, Drinks are on me!
|
0

What you're passing self.SelectedVariable isn't an array. Should you not be calling it just an observable? Otherwise, you need to be adding your results with self.SelectedVariable.push(resultObject).

2 Comments

the vardata is obviously not parsing correctly...thing is, you are converting self.SelectedVariable to JSON, but your vardata is still a JS object...I would recomment you try just passing the object...eg data: ko.toJSON(self.SelectedVariable()
Ok I understand, but not to sure about how to implement correctly?
0

By using this Ajax call

       $.ajax({
        url: "/api/Variable?Del=0",
        contenttype: "application/x-www-form-urlencoded",
        data: "=" + ko.toJSON(self.SelectedVariable),
        type: "PUT",
        dataType: "JSON",
        timeout: 10000,
        success: function (Result) {

        },
        error: function (xhr, status) {
            alert(status + " - " + xhr.responseText);
        }
    });

and then using Newtonsoft to deserialize the object on WebAPI using this method:

public void Put([FromUri] int Del, [FromBody]string vardata)
{

    Variables vari = JsonConvert.DeserializeObject<Variables>(vardata.Substring(1, vardata.Length-2));

    var Item = (from c in TMIRE.Variables
                where c.VariableID == vari.VariableID
                select c).First();

    if (Del == 0)
    {
        Item.VariableDateUpdated = DateTime.Now;
        Item.VariableName = vari.VariableName;
        Item.VariableDescription = vari.VariableDescription;
        Item.VariableValue = vari.VariableValue;
        Item.VariableType = vari.VariableType;
    }
    else
    {
        Item.VariableDateUpdated = DateTime.Now;
        Item.VariableActive = false;
    }

    TMIRE.SaveChanges();
}

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.