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
Pass the
JsonSerializerOptions
as a parameter when creating theJson
object to make property’s name case-sensitive during deserialization. TheJsonSerializerOptions
hasPropertyNameCaseInsensitive
property that by default set tofalse
. This will prevent the Json serializer to change names to be camel-cased.JsonSerializerOptions Class
Please check the return json from controller:
You will find that the key is
urlOne
instead ofUrlOne
.Javascript is case sensitive, So you need to change your code like: