skip to Main Content

I have a ajax post that I need to redirect to redirect url on success.
In the browser debugger I do c the correct url but I’m always getting "MYURL/undefined".

$.ajax({
        type: 'POST',
        url: "/NewsLetter/Create",
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: data,

        success: function(result) { //debug >result={urlOne:'https://localhost:7077'}
            //  alert('Successfully received Data ');

            if (result.UrlOne !== undefined) {
                window.location.replace(result.UrlOne);
            } else {
                window.location.replace(result.UrlTwo);
            }
            console.log(result);
        },
        error: function(error) {
            alert('Failed to receive the Data');
            console.log(JSON.stringify(error));
            console.log('Failed ');
        }
    });

In my controller:

if (ModelState.IsValid && isNewUser == null)
{
   //remove for clear code
    return Json(new { UrlOne = Url.ActionLink("Index","Home")});
}

TempData["ErrorMes"] = "You are allready register";
return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") });

2

Answers


  1. Pass the JsonSerializerOptions as a parameter when creating the Json object to make property’s name case-sensitive during deserialization. The JsonSerializerOptions has PropertyNameCaseInsensitive property that by default set to false. This will prevent the Json serializer to change names to be camel-cased.

    
    var options = new System.Text.Json.JsonSerializerOptions();
    
    if (ModelState.IsValid && isNewUser == null)
    {
       //remove for clear code
        return Json(new { UrlOne = Url.ActionLink("Index","Home")}, options);
    }
    
    TempData["ErrorMes"] = "You are allready register";
    return Json(new { UrlTwo = Url.ActionLink("_RegNews", "NewsLetter") }, options);
    

    JsonSerializerOptions Class

    Login or Signup to reply.
  2. Please check the return json from controller:

    enter image description here

    You will find that the key is urlOne instead of UrlOne.

    Javascript is case sensitive, So you need to change your code like:

    if (result.urlOne !== undefined) {
                        window.location.replace(result.urlOne);
                    } else {
                        window.location.replace(result.urlTwo);
                    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search