1

I have this method and as you can see I modified it:

[HttpPut]
public HttpResponseMessage PutSIMSData(string langid, byte period, byte year, string data, int userId, SIMSData simsdata)//HttpRequestMessage req)
{
    try
    {
        //SIMSData simsdata = new SIMSData();
        //string jsonContent = req.Content.ReadAsStringAsync().Result;
        //simsdata = JsonConvert.DeserializeObject<SIMSData>(jsonContent);
        //SIMSData simsdata = db.SIMSDataDbSet.Find(langid, period, year);

        if (ModelState.IsValid && 
            simsdata.LanguageID == langid &&
            simsdata.PeriodID == period &&
            simsdata.YearID == year)
        {
            //simsdata.UserID = userId;
            //simsdata.Data = data;
            db.Entry(simsdata).State = EntityState.Modified;
            db.SaveChanges();

            return Request.CreateResponse(HttpStatusCode.OK, simsdata);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest, simsdata);
        }
    }
    catch (Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}

But the problem is, I keep getting Error 500, i.e I am trying to insert row with key combination which already exists in the table.

My table is a composite key table, 3 keys, LanguageID, PeriodID, YearID, Data and UserId are fields that should be updated.

My ajax call looks like this:

updateSIMSDataWithAllParams: function (lang, period, year, data, userId) {
    jq.ajax({
        context: simsDataView,
        contentType: 'application/json; charset=utf-8',
        type: "PUT",
        url: "/api/SIMSData",
        dataType: "json",

        data: JSON.stringify({
            LanguageID: lang,
            PeriodID: period,
            YearID: year,
            Data: data,
            UserID: userId
        }),

        beforeSend: function (jqXHR, settings) {
            simsDataView.setStatusMsg(messages.listingTreeDataMsg, "blue");
        },

        success: function (data, textStatus, jqXHR) {

        },

        error: function (jqXHR, textStatus, errorThrown) {
            errorsMsgTxt.text("SIMS Tree: " + textStatus + ". Error: " + errorThrown + " ");
        }
    });
},

What am i doing wrong?

Vlad
  • 2,739
  • 7
  • 49
  • 100
  • What appens when you use `simsdata = db.SIMSDataDbSet.Find(langid, period, year);`? Also I don't understand why `simsdata` is a parameter of the function. – Omar Muscatello Aug 04 '17 at 08:21
  • Your `if ` block will never be executed (the values of `langid`, `period`, and `year` and will always be their defaults because you never send values for them) –  Aug 04 '17 at 08:22
  • What do you mean I don't send them, check the ajax call, data object – Vlad Aug 04 '17 at 08:36
  • 1
    Your sending name/value pairs for `LanguageID`, `PeriodID` etc, not `langid`, `period` etc –  Aug 04 '17 at 08:39
  • Possibly you are `PUT`-ting the HTTP method request wrong: https://stackoverflow.com/questions/107390/whats-the-difference-between-a-post-and-a-put-http-request. I think you're sending complex object that contains wrong keys (`langid` instead of `LanguageID`). – Tetsuya Yamamoto Aug 04 '17 at 08:40
  • Turns out I have had an error in my JS code. I have been calling my POST function instead of my PUT function. – Vlad Aug 04 '17 at 09:36

2 Answers2

0

I think the code you posted is a derivation of some attempts and, from my opinion, it is a little confusing.

Try this

[HttpPut]
public HttpResponseMessage PutSIMSData(string langid, byte period, byte year, string data, int userId)
{

    if (ModelState.IsValid)
    {
        try
        {
            SIMSData simsdata = db.SIMSDataDbSet.Find(langid, period, year);

            if(simsdata == null) {
               // entity not found
            }

            // Updating values
            simsdata.UserID = userId;
            simsdata.Data = data;

            db.Entry(simsdata).State = EntityState.Modified;
            db.SaveChanges();

            return Request.CreateResponse(HttpStatusCode.OK, simsdata);
        } 
        catch (Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }

    else
    {
         return Request.CreateResponse(HttpStatusCode.BadRequest, simsdata);
    }
}

Ajax Call:

updateSIMSDataWithAllParams: function (lang, period, year, data, userId) {
  jq.ajax({
      context: simsDataView,
      contentType: 'application/json; charset=utf-8',
      type: "PUT",
      url: "/api/SIMSData",
      dataType: "json",

      data: JSON.stringify({
          langid: lang,
          period: period,
          year: year,
          data: data,
          userId: userId
      }),

      beforeSend: function (jqXHR, settings) {
          simsDataView.setStatusMsg(messages.listingTreeDataMsg, "blue");
      },

      success: function (data, textStatus, jqXHR) {

      },

      error: function (jqXHR, textStatus, errorThrown) {
          errorsMsgTxt.text("SIMS Tree: " + textStatus + ". Error: " + errorThrown + " ");
      }
  });
},
Omar Muscatello
  • 1,256
  • 14
  • 25
0

Turns out I have been calling my Save/POST method all the time instead of my Update/PUT method. I have an AJAX call which fetches data and it shows a Save button. When i press my Save button, the data I have fetched contains property called "hasData" which when true, pressing the Save button would run Update() function and if "hasData" is false, pressing the Save button would call my Save() function. The error I had was, I was checking the wrong JavaScript object for this "hasData" property.

I use this code in my controller now:

    [HttpPut]
    public HttpResponseMessage PutSIMSData(HttpRequestMessage req)
    {
        try
        {
            SIMSData simsdata = new SIMSData();
            string jsonContent = req.Content.ReadAsStringAsync().Result;
            simsdata = JsonConvert.DeserializeObject<SIMSData>(jsonContent);

            if (ModelState.IsValid)
            {
                db.Entry(simsdata).State = EntityState.Modified;
                db.SaveChanges();

                return Request.CreateResponse(HttpStatusCode.OK, simsdata);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, simsdata);
            }
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }
Vlad
  • 2,739
  • 7
  • 49
  • 100