0

I've taken a look at the other VaryByParam questions, but I haven't been able to find the answer to my question. I have an MVC site that has the following action defined:

[OutputCache(Duration = 30, VaryByParam = "TargetID")]
public JsonResult IsThingAllowed(int TargetID)
{
    bool isAllowed = IsAllowed(TargetID);

    return Json(isAllowed, JsonRequestBehavior.AllowGet);
}

No matter what comes in for TargetID, the cached value gets returned. However, if I change TargetID to be *, it works as expected (cached values vary by TargetID):

[OutputCache(Duration = 30, VaryByParam = "*")]

Here's the AJAX call:

$.ajax({
    url: "/MyController/IsThingAllowed",
    type: "POST",
    data: JSON.stringify({ "TargetID": id }), // This is definitely varying!
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data, textStatus, xhr) {

        updateThing(data);
    },
    error: function (xhr, textStatus, error) {

    }
});

What am I doing wrong when the parameter is explicitly named?

EDIT: Works if we use GET instead of POST.. but POST obviously works, since it works when we use *.

Here's it working with GET:

 $.ajax({
     url: "/MyController/IsThingAllowed",
     type: "GET",
     data: { TargetID: id },
     dataType: "json",
     contentType: "application/json; charset=utf-8",
     success: function (data, textStatus, xhr) {

         updateThing(data);
     },
     error: function (xhr, textStatus, error) {

     }
 });
zimdanen
  • 5,508
  • 7
  • 44
  • 89
  • Shouldn't it be `data: {TargetID: myTargetID},`? – Ilia G Feb 06 '13 at 21:00
  • @IliaG: `myTargetID` is `var myTargetID = JSON.stringify({ "TargetID": id });` - I'll update the question for clarity. – zimdanen Feb 06 '13 at 21:09
  • but... not it is `CorrespondentID`? :) – Ilia G Feb 06 '13 at 21:27
  • @IliaG: Fixed. Sanitizing for web. (Removing domain information.) – zimdanen Feb 06 '13 at 21:28
  • I am still confused... why are you passing stringified version to the `data`? This is basically the body of you request. It should be URL encoded, not JSON encoded. In either case `VaryByParam` would only apply to GET or POST parameter, not a field in a JSON structure. – Ilia G Feb 06 '13 at 21:47
  • Then what makes it work when using `GET` or using `*` with `POST`? (In reply to your first question - I'm fixing a bug; didn't write the initial code.) – zimdanen Feb 06 '13 at 21:50
  • @IliaG: Although, for `GET` to work, I did have to switch to JSON structure instead of stringifying it. (Updated question with relevant change.) – zimdanen Feb 06 '13 at 21:57
  • make sure you change your `contentType`. Remove it to default to url-encoded. – Ilia G Feb 07 '13 at 14:38
  • @IliaG: Thanks; that seems to allow the client (browser) to cache the return value, so fewer trips to the server. – zimdanen Feb 07 '13 at 15:46

0 Answers0