0

I have an Ajax function that calls a get request. I am constructing the url by using data values from ViewBag, for some reason am not understading Ajax keeps on removing the values from the special character to the end. This is my Ajax

 $.ajax({
      url: 'api/getProvinceDatByUserID/@ViewBag.reportinPeriod&UserId=@ViewBag.userId&provinceName=@ViewBag.provinceName',
      type: 'GET',
      success: function (data) {}
});

The expected url should look like

api/getProvinceDatByUserID/Jun-2022&UserId=f8f61c2e-6cf3-454f-b3bd-bf6deae205a4&provinceName=ZAMBÉZIA

but Ajax trims the provinceName to

api/getProvinceDatByUserID/Jun-2022&UserId=f8f61c2e-6cf3-454f-b3bd-bf6deae205a4&provinceName=ZAMB&

hence my requesting failing,

How can I set Ajax to stop trimming and removing the special values and characters after it? Any help is appreciated

Update 1

I have to add the encodeUri still same trimming

url: 'api/getProvinceDatByUserID/@ViewBag.reportinPeriod&UserId=@ViewBag.userId&provinceName='+encodeURI('@ViewBag.provinceName')

Update 2

After adding encodeURIComponent to the url am no longer getting ZAMB& but am getting ZAMBÉZIA. Does ajax understand What is the ZAMBÉZIA the symbol ontop of letter E ?

arriff
  • 399
  • 1
  • 10
  • 30
  • Try using `encodeURI` – first last Jul 20 '22 at 15:23
  • Hi @firstlast i have tried that, still trimming – arriff Jul 20 '22 at 15:39
  • https://stackoverflow.com/questions/7756464/how-do-i-render-html-from-the-viewbag-using-mvc3-razor – Quentin Jul 20 '22 at 15:40
  • You've misidentified the problem. It occurs long before Ajax gets involved. Viewbag is encoding the string as HTML but you are inserting it into a URL in JS not into HTML. You need to encode the string as a URL component (how you do that in viewbag, I've no idea, I've never used it). – Quentin Jul 20 '22 at 15:40
  • encodeURIComponent – IT goldman Jul 20 '22 at 16:03
  • Hi @Quentin, am passing it correctly, that is how am accessing the userid and date. @ITgoldman am getting this now `ZAMBÉZIA` – arriff Jul 20 '22 at 16:45

1 Answers1

1

this is how I finally solved by issue

 var provinceName = @Json.Serialize(ViewBag.provinceName);

then access the variable with the preserved special characters. and the final url looks like

 url: 'api/getProvinceDatByUserID/@ViewBag.reportinPeriod&UserId=@ViewBag.userId&provinceName='+ provinceName , 
arriff
  • 399
  • 1
  • 10
  • 30