'Viewbag content does not appear

I have an APS.Net web app Razor view where I attempt to display the Viewbag.errormessage.

The action method populates the viewbag but the view does not show the error message that is in the viewbag. It does not appear. Why?

The paragraph to which the Viewbag is attached to does not even appear per the 2nd pic. In the 1st pic, I can see that is there.

I also tried using 'TempData' but it produces the same result - not appearing.

enter image description here

enter image description here

Here is the action method (simplified):

    [HttpPost]
    public async Task<ActionResult> DeleteUserAccount(string userName, string 
    password)
    {
        try
        {
            if (string.IsNullOrEmpty(userName) || 
            string.IsNullOrEmpty(password))
            {
                ViewBag.errormessage = "The 'user name' or 'password' is 
                invalid - empty. Please try again.";
            }
            else
            {
                // Cast.
                if ((string)Session["UserName"] == userName)
                {

                }
                else
                {
                   ViewBag.errormessage = "Your 'user name' is invalid. It 
                   is not the same as the 'user name' used at original sign 
                   in. Please try again.";
                }
            }
        }
        catch (Exception ex1)
        {

        }

        return View();
    }

Here is the view:

@Html.AntiForgeryToken()

<div class="login-panel">
    @if (ViewBag.errormessage != null)
    {
        <p class="alert alert-danger" id="errorMessage">@ViewBag.errormessage</p>
    }

    <div class="form-group">
        <div class="col-md-12 col-xs-12">
            <h2>Delete Account</h2>
            <br />
            <h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
            <br />
            <h4 class="verify"><strong>Please provide the following:</strong></h4>
        </div>
    </div>
    <br />
    <div class="form-group">
        <div class="col-md-12 col-xs-12">
            <br />
            <label class="manadatory" for="UserName">User Name</label>
            <input id="UserName" type="text" value="" name="UserName">
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-12 col-xs-12">
            <br />
            <label class="manadatory" for="Password">Password</label>
            <input id="Password" type="text" value="" name="Password">
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-0 col-md-10">
            <br />
            <input class="btn btn-primary deleteUserAccount" value="Delete Account">
            @Html.ActionLink("Cancel", "Index", "User", null, new { @class = "btn btn-info" })
        </div>
    </div>
</div>

<div class="modal fade" id="myModal4" role="dialog" display="none">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body" style="padding:10px;">
                <h4 class="text-center">Are you sure you want to permanently delete your account and all it contains?  Continue ?</h4>
                <div class="text-center">
                    <a class="btn btn-info btn-yes4">Yes</a>
                    <a class="btn btn-default btn-no4">No</a>
                </div>
            </div>
        </div>
    </div>
</div>

@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Styles.Render("~/Content/css")

<script type="text/javascript">
$(document).ready(function () {
    $(".deleteUserAccount").click(function (e) {
        var holdUserName = $('#UserName').val();
        var holdPassword = $('#Password').val();

        $("#myModal4").modal({
            backdrop: 'static',
            keyboard: false
        });

        $(".btn-yes4").click(function () {
            $("#myModal4").modal("hide");

            // Do the delete.
            // - Pass the 2 fields.
            $.ajax({
                type: 'POST',
                url: '@Url.Action("DeleteUserAccount", "User")',
                data: { userName: holdUserName, password: holdPassword},
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
                }
            });

            // Return.
            return true;
        });

        $(".btn-no4").click(function () {
            $("#myModal4").modal("hide");
            return false;
        });

        $("#myModal4").on('hidden.bs.modal', function () {
            $("#myModal4").remove();
        });
    });
})
</script>


Solution 1:[1]

https://dotnetfiddle.net/U6HGHD Ajax makes a call and does not re-render a page

Controller

[HttpPost]
//I made method snchronous as it has no await, and there are no resources to add await to
public ActionResult DeleteUserAccount(string userName, string password)
{
    var errorMessage = String.Empty;
    try
    {

        if (string.IsNullOrEmpty(userName) ||
        string.IsNullOrEmpty(password))
        {
            //since this method is ajax, the view will not re-render, so errors need
            //to go into return value.
            //ViewBag.errormessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
            errorMessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
        }
        else
        {
            // Cast.
            if ((string)Session["UserName"] == userName)
            {

            }
            else
            {
                //ViewBag.errormessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
                errorMessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
            }
        }
    }
    catch (Exception ex1){}

    //return View();
    //since this is ajax, I am returning a json
    return Json(errorMessage, JsonRequestBehavior.AllowGet);
}

public ActionResult Index19()
{
    return View();
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index19</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js" integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf" crossorigin="anonymous"></script>
    <script type="text/javascript">
    $(document).ready(function () {
        $(".deleteUserAccount").click(function (e) {
            //put this in here
            $("#myModal4").modal({
                backdrop: 'static',
                keyboard: false
            });
        //fixed the following line
        });


        $(".btn-yes4").click(function () {
            //put these here
            var holdUserName = $('#UserName').val();
            var holdPassword = $('#Password').val();

            $("#myModal4").modal("hide");

            // Do the delete.
            // - Pass the 2 fields.
            $.ajax({
                type: 'POST',
                url: '@Url.Action("DeleteUserAccount", "Home")',
                data: { userName: holdUserName, password: holdPassword },
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                success: function (data) {
                    if (data.length > 0) {
                        $("#errorMessage").css("display", "block");
                    }
                    else {
                        $("#errorMessage").css("display", "none");
                    }
                    $("#errorMessage").text(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
                }
            });

            // Return.
            return true;
        });

        $(".btn-no4").click(function () {
            $("#myModal4").modal("hide");
            return false;
        });

        //$("#myModal4").on('hidden.bs.modal', function () {
        //    $("#myModal4").remove();
        //});
    });
    </script>
</head>
<body>
    @Html.AntiForgeryToken()

    <div class="login-panel">
        @*took out condition, and started with style none*@
        @*@if (ViewBag.errormessage != null)
        {*@
            <p class="alert alert-danger" id="errorMessage" style="display:none">@ViewBag.errormessage</p>
        @*}*@

        <div class="form-group">
            <div class="col-md-12 col-xs-12">
                <h2>Delete Account</h2>
                <br />
                <h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
                <br />
                <h4 class="verify"><strong>Please provide the following:</strong></h4>
            </div>
        </div>
        <br />
        <div class="form-group">
            <div class="col-md-12 col-xs-12">
                <br />
                <label class="manadatory" for="UserName">User Name</label>
                <input id="UserName" type="text" value="" name="UserName">
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-12 col-xs-12">
                <br />
                <label class="manadatory" for="Password">Password</label>
                <input id="Password" type="text" value="" name="Password">
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-0 col-md-10">
                <br />
                <input class="btn btn-primary deleteUserAccount" value="Delete Account">
                @Html.ActionLink("Cancel", "Index", "User", null, new { @class = "btn btn-info" })
            </div>
        </div>
    </div>

    <div class="modal fade" id="myModal4" role="dialog" display="none">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-body" style="padding:10px;">
                    <h4 class="text-center">Are you sure you want to permanently delete your account and all it contains?  Continue ?</h4>
                    <div class="text-center">
                        <a class="btn btn-info btn-yes4">Yes</a>
                        <a class="btn btn-default btn-no4">No</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1