[英]How to check null value within TempData Razor MVC that written inside js code
我正在尝试检查用JavaScript代码编写的TempData Razor MVC中的空值,但不幸的是它不起作用。
无论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调用中使用它。 剃刀代码在发送到视图之前在服务器上进行了解析,因此@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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.