我正在尝试检查 TempData Razor MVC 中编写的 JavaScript 代码中的 null 值,但不幸的是它不起作用。
无论 TempData 值是否为 null,条件始终为 true
if ('@TempData["Error"]' != null) {
alert("Problem" + '\n' + "@TempData["error"]");
} else {
alert("The file Uploaded Successfully");
}
我如何检查? 如果有替代方案,请告诉我。
谢谢。
编辑:
上面的代码是JQuery ajax请求代码的一部分。
<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>
最佳答案
您引用该值,因此如果 @TempData["Error"]
为 null
,它将转换为空字符串。您可以使用 .length
检查它,但最好使用
var error = @Html.Raw(Json.Encode(TempData["Error"]))
if (error) {
alert("Problem" + '\n' + error);
} else {
alert("The file Uploaded Successfully");
}
根据问题的修订上下文,您在 ajax 调用中使用了它。 Razor 代码在发送到 View 之前会在服务器上进行解析,因此 @TempData["Error"]
返回页面首次呈现时的值。只是因为您可能在 Upload()
方法中设置 TempData
的值,因此不会更新它。
您的方法应该返回包含错误的 json,以便您可以在成功回调中显示它。例如,您的方法可能是
public ActionResult Upload(...)
{
return Json(null); // to indicate success, or
return Json("oops, something went wrong);
}
然后在ajax回调中
success: function (response) {
if (response) {
alert(response);
} else {
alert("The file Uploaded Successfully");
}
关于javascript - 如何检查 TempData Razor MVC 中编写的 js 代码中的 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42265187/