Reputation: 315
I'm Trying to check null value within TempData Razor MVC that written inside javascript code, but unfortunately it doesn't work.
whether TempData value is null or not, the condition is always true
if ('@TempData["Error"]' != null) {
alert("Problem" + '\n' + "@TempData["error"]");
} else {
alert("The file Uploaded Successfully");
}
How i can check? if there are alternatives, please let me know.
thanks.
Edit:
The code above is part of JQuery ajax request code.
<script>
$body = $("body");
$(document).on({
ajaxStart: function () { $body.addClass("loading"); },
ajaxStop: function () { $body.removeClass("loading"); }
});
$(document).ready(function () {
$("#upload").click(function () {
var data = new FormData();
//Add the Multiple selected files into the data object
var files = $("#files").get(0).files;
for (i = 0; i < files.length; i++) {
data.append("files" + i, files[i]);
}
//data.append("id", '');
data.append("id", '@Model.NoteID');
//Post the data (files) to the server
if (files.length > 0) {
$.ajax({
type: 'POST',
url: "@Url.Action("Upload","Files")",
data:data,
contentType: false,
processData: false,
success: function (data) {
if ('@TempData["Error"]' != null) {
alert("Problem" + '\n' + "@TempData["error"]");
} else {
alert("file uploaded successfully");
}
},
error: function () {
alert("Fail");
},
});
}
});
});
</script>
Upvotes: 2
Views: 3413
Reputation:
Your quoting the value, so if @TempData["Error"]
is null
, it translates to a empty string. You could check it using .length
but it would be better to use
var error = @Html.Raw(Json.Encode(TempData["Error"]))
if (error) {
alert("Problem" + '\n' + error);
} else {
alert("The file Uploaded Successfully");
}
Based on the revised context of the question, your using this inside an ajax call. Razor code is parsed on the server before its sent to the view, so @TempData["Error"]
returns the value when when the page is first rendered. Just because you may be setting the value of TempData
in the Upload()
method does not update it.
Your method should be returning json containing the error so that you can then display it in the success callback. For example, your method might be
public ActionResult Upload(...)
{
return Json(null); // to indicate success, or
return Json("oops, something went wrong);
}
and then in the ajax callback
success: function (response) {
if (response) {
alert(response);
} else {
alert("The file Uploaded Successfully");
}
Upvotes: 4