Hi jewel,
You need know the following things:
-
TempData
is server-side storage, while AJAX responses operate on the client side. TempData
won’t be available in the AJAX callback directly.
- You cannot use
RedirectToAction
in the backend, because ajax cannot handle redirect operation from backend.
- No matter the validation is valid or not in server side,
RedirectToAction
(e.g Ok
/Json
...) is a successful response for ajax call back. You can return BadRequest to make the response error for ajax, and use .responseText
in ajax error function to get the response message.
A solution is to modify your InserData
action to return a JSON response instead of redirecting. This way, you can directly return the TempData
message in the response, allowing AJAX to capture it and display it in the alert.
View:
<script>
function addata() {
var objdata =
{
CompnayName: $('#Compnay_Name').val(),
contuctNo: $('#ContuctNo').val(),
};
$.validator.unobtrusive.parse($("#my_form"));
if ($("#my_form").valid()) {
$.ajax({
type: 'POST',
url: '/Company/InserData',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: objdata,
success: function (res) {
alert(res) //here i want use tempdata
window.location.href = "/Company/Index";
},
error: function (xhr) {
alert(xhr.responseText) //here i want use tempdata
window.location.href = "/Company/Index";
}
});
}
}
</script>
Controller:
public IActionResult InserData(tbl_Company np)
{
if (ModelState.IsValid)
{
TempData["sms"] = "Data Save";// i want so see this data as message for jquery alert
return Json(TempData["sms"]);
}
else
{
TempData["sms"] = "Data Not Save";// i want so see this data as message for jquery alert
return BadRequest(TempData["sms"]);
}
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Rena