簡體   English   中英

如何檢查在js代碼中編寫的TempData Razor MVC中的空值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM