2

I have a javascript object that looks like...

filter = {
   lastchanged: 5,
   Location: {
      Country: 5,
      Province: 3
   }
}

I'm making the ajax call like so...

jQuery.ajax({ url: search_url, data: filter, dataType: "html" })

I want the object properties to be serialized like so...

/my-controller?lastchanged=5&Location.Country=5&Location.Province=3

However they are currently serializing as...

/my-controller?lastchanged=5&Location%5BCountry%5D=5&Location%5BProvince%5D=3

which is not working with the MVC binding.

Is there a correct way to tell jQuery to encode the parameters the first way, exactly as they would be if it was a regular form submission?

user1751825
  • 4,029
  • 1
  • 28
  • 58
  • Could you not use HttpPost? – Win Jul 20 '17 at 15:32
  • I could use HttpPost, but this would kind of be breaking the REST paradigm. It would also be bad for browser caching. – user1751825 Jul 20 '17 at 15:35
  • I'm using CloudFront CDN to cache as much of the queries as possible, It can't cache if I use post. – user1751825 Jul 20 '17 at 15:37
  • Ideally, you want to flatten those property names, and use *ViewModel* at server side. Then map *ViewModel* to *Domain/Entity objecs* using AutoMapper. – Win Jul 20 '17 at 15:45
  • I found a solution by flattening the object in javascript, just before calling the ajax get. As detailed here... https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects – user1751825 Jul 20 '17 at 16:04
  • This avoided the need to change anything at the server side. – user1751825 Jul 20 '17 at 16:05

1 Answers1

0

I'm unaware of an official/jQuery way to get the precise formatting you need, but you could always do it yourself using some String Replace All operations.

Demo:

function ReplaceAll(str, search, replacement) {
  return str.split(search).join(replacement);
};

function FormatForAjaxGET(obj) {
  var result = $.param(obj);
  result = ReplaceAll(result, "%5B", ".");
  result = ReplaceAll(result, "%5D=", "=");
  return result;
}

var filter = {
  lastchanged: 5,
  Location: {
    Country: 5,
    Province: 3
  }
};
console.log(FormatForAjaxGET(filter));

// And to make the call, do
// jQuery.ajax({ url: search_url + "?" + FormatForAjaxGET(filter), dataType: "html" });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • Thanks @Peter, This looks like it would work in this case. I ended up using a more general purpose flattening function I found at https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects – user1751825 Jul 20 '17 at 16:07