Asp.net partial view - setting html and css after clicked - not changing it's state

Viewed 411

Asp.net partial view - setting html and css after clicked - not changing it's state

I have a parent view with an embedded partial view (the thumbs and counts).

The partial view has 2 thumbs and 2 counts.

enter image description here

The up thumb is disabled and has a count = 1. Also green to indicate it was previously selected. The down thumb is enabled and has a count = 0. Also black to indicate it can be selected.

When I click on the down thumb, I execute a JavaScript function which calls the controller's action method to set the counts on the database accordingly, sets session variables and returns the partial view with the updated view model. At this point I would expect the view to change it's state - the counts and disable/enable the appropriate thumbs.

However, it does not. Why? It does NOT reflect the counts (in the html) nor go back into the $(document).ready(function () which executes the functions to set the appropriate visual changes to the thumbs (disable/enable and change the color).

So, instead I took a 2nd approach. After the successful call to the action method, I use session variables in JavaScript functions to reflect the counts (in the html) and to set the appropriate visual changes to the thumbs (disable/enable and change the color). I see I get threw the and execute the settings. They are all the correct values and are applied but NO state change is reflected on the partial view.

Why does it not take the settings - refresh the partial view to reflect the count and disable/enable the appropriate thumb.?

enter image description here

I would expect the partial view to look like this below. The up thumb enabled and a count = 0 and the down thumb a count = 1 and disabled.

enter image description here


Here is the partial view:

@model GbngWebClient.Models.LikeOrDislikeVM

<style>
.fa {
    cursor: pointer;
    user-select: none;
}

    .fa:hover {
        color: blue;
    }

/* I added. */
.my-size {
    font-size: 20px;
}

.my-button {
    border: none;
    padding: 8px 10px;
    float: left;
    font-size: 16px;
    margin: 4px 2px;
    background-color: white;
}
</style>


<div class="row">
    <div>
        <button class="blogLike my-button fa fa-thumbs-up"><span class="my-size, likeCount"> : @Model.LikeCount </span></button>
        <button class="blogDisLike my-button fa fa-thumbs-down"><span class="my-size, dislikeCount"> : @Model.DisLikeCount</span></button>
    </div>
</div>

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

<script type="text/javascript">
    $(document).ready(function () {
        // For testing:
        console.log('Here at ready. ');

        // JavaScript needs it as 'false'. So using these 'const' to convert them.
        const False = false, True = true;

        // Set the initial disabled attributes and color.
        SetLike(@Model.LikeDisabled);
        SetDisLike(@Model.DisLikeDisabled);

        // For when clicking the BlogLike thumb.
        $('.blogLike').on('click', function () {
            // Call the BlogPublished controllers action method to set the blog's LikeCount.
                 
            $.ajax({
                type: 'POST',
                data: { likeOrDislikeIndicator: "L" },
                success: function (response) {
                    // Call to the server side to get the session variable and then set the HTML.
                    GetSessionVarAndSetHtml("LikeDisabled");
                    GetSessionVarAndSetHtml("DisLikeDisabled");
                    GetSessionVarAndSetHtml("LikeCount");
                    GetSessionVarAndSetHtml("DisLikeCount");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                   alert("Critical Error");
                }
            })
        });

        // For when clicking the BlogDisLike.
        $('.blogDisLike').on('click', function () {
            // Call the BlogPublished controllers action method to set the blog's DisLikeCount.
        
            $.ajax({
                type: 'POST',
                url: '@Url.Action("SetBlogLikeOrDisLike", "BlogPublished")',
                data: { likeOrDislikeIndicator: "D" },
                success: function (response) {
                    // Call to the server side to get the session variable and then set the HTML.
                    GetSessionVarAndSetHtml("LikeDisabled");
                    GetSessionVarAndSetHtml("DisLikeDisabled");
                    GetSessionVarAndSetHtml("LikeCount");
                    GetSessionVarAndSetHtml("DisLikeCount");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                   alert("Critical Error");
                }
            })
        });

        //-----------------------------------------------------------------------------------------
        // Call to the server side to get the session variables. Then set the Html accordingly.
        //-----------------------------------------------------------------------------------------
        function GetSessionVarAndSetHtml(toBeProcessed) {
            // For testing:
            console.log('Here at GetSessionVarAndSetHtml. ');

             $.ajax({
                type: 'GET',
                url: '@Url.Action("GetSessionVar", "BlogPublished")',
                data: { toBeProcessed: toBeProcessed },
                success: function (response) {
                   console.log('Response:  ' + response);

                    if (toBeProcessed == "LikeDisabled")
                    {
                       // Set the Html. Response will be either true or false.
                       SetLike(response);
                    };

                    if (toBeProcessed == "DisLikeDisabled") {
                        // Set the Html. Response will be either true or false.
                        SetDisLike(response);
                    };

                    if (toBeProcessed == "LikeCount") {
                        // Set the Html. Response will be an integer.
                        SetLikeCount(response);
                    };

                    if (toBeProcessed == "DisLikeCount") {
                        // Set the Html. Response will be an integer.
                        SetDisLikeCount(response);
                    };
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert("Critical Error");
             }
           })
        }

        //--------------------------------------------------------------------------------------
        // Set the disabled attribute to true or false and set color.
        //--------------------------------------------------------------------------------------
        function SetLike(disabledSwitch) {
            // For testing:
            console.log('Here at Setlike. ' + disabledSwitch);

            $(".blogLike").attr('disabled', disabledSwitch);

            if (disabledSwitch == true )
            {
                // Show by color that it was liked.
                $(".blogLike").css('color', 'green');
            }

            if (disabledSwitch == false)
            {
                // Show by color that it can be clicked.
                $(".blogLike").css('color', 'black');
            }
        }

        //--------------------------------------------------------------------------------------
        // Set the disabled attribute to true or false and set color.
        //--------------------------------------------------------------------------------------
        function SetDisLike(disabledSwitch) {
            // For testing:
            console.log('Here at SetDisLike. ' + disabledSwitch);

            $(".blogDisLike").attr('disabled', disabledSwitch);

            if (disabledSwitch == true)
            {
                // Show by color that it was disliked.
                $(".blogDisLike").css('color', 'green');
            }

            if (disabledSwitch == false)
            {
                // Show by color that it can be clicked.
                $(".blogDisLike").css('color', 'black');
            }
        }

        //--------------------------------------------------------------------------------------
        // Set the like count.
        //--------------------------------------------------------------------------------------
        function SetLikeCount(count) {
            // For testing:
            console.log('Here at SetLikeCount. ' + count);

            $(".likeCount").val(count);
        }

        //--------------------------------------------------------------------------------------
        // Set the dislike count.
        //--------------------------------------------------------------------------------------
        function SetDisLikeCount(count) {
            // For testing:
            console.log('Here at SetDisLikeCount. ' + count);

            $(".dislikeCount").val(count);
        }
    });
</script>

Here is the action method:

    [HttpPost]
    public async Task<ActionResult> SetBlogLikeOrDisLike(string likeOrDislikeIndicator)
    {
        BLL_BlogPublished bll_BlogPublished = new BLL_BlogPublished();

        SetBlogLikeOrDisLikeResult setBlogLikeOrDisLikeResult = new SetBlogLikeOrDisLikeResult();

        LikeOrDislikeVM likeOrDislikeVM = new LikeOrDislikeVM();

        try
        {
            // Update the 'like count' or 'dislike count' in the Blog table and (update/insert) a corresponding entry in the UserBlogPreference table.
            setBlogLikeOrDisLikeResult = await bll_BlogPublished.SetBlogLikeOrDisLike(Convert.ToInt32(Session["BlogId"]), Convert.ToInt32(Session["UserId"]), Session["UserName"].ToString(), likeOrDislikeIndicator);

            // Check if an error occurred in the web api.
            if (setBlogLikeOrDisLikeResult.ApiErrorMessage == null)
            {
                 if (setBlogLikeOrDisLikeResult.Status == 1)
                {
                    //  Set these view model properties model from session variables.
                    likeOrDislikeVM.BlogId = Convert.ToInt32(Session["BlogId"]);
                    likeOrDislikeVM.UserId = Convert.ToInt32(Session["UserId"]);

                    // Set these view model properties from what was returned.
                    likeOrDislikeVM.LikeCount = setBlogLikeOrDisLikeResult.LikeCount;
                    likeOrDislikeVM.DisLikeCount = setBlogLikeOrDisLikeResult.DisLikeCount;
                    likeOrDislikeVM.LikeDisabled = setBlogLikeOrDisLikeResult.LikeDisabled;
                    likeOrDislikeVM.DisLikeDisabled = setBlogLikeOrDisLikeResult.DisLikeDisabled;

                    // Set the session variables that will be used in the partial view.
                    SetIntegerSessionVar("LikeCount", setBlogLikeOrDisLikeResult.LikeCount);
                    SetIntegerSessionVar("DisLikeCount", setBlogLikeOrDisLikeResult.DisLikeCount);
                    SetBooleanSessionVar("LikeDisabled", setBlogLikeOrDisLikeResult.LikeDisabled);
                    SetBooleanSessionVar("DisLikeDisabled", setBlogLikeOrDisLikeResult.DisLikeDisabled);
                }
                else if (setBlogLikeOrDisLikeResult.Status == 2)
                {
                    ViewBag.errormessage = "Process Violation: The blog does not exist.";
                }
                else if (setBlogLikeOrDisLikeResult.Status == 3)
                {
                    ViewBag.errormessage = "Process Violation: The user does not exist.";
                }
                else if (setBlogLikeOrDisLikeResult.Status == 4)
                {
                    ViewBag.errormessage = "Process Violation: An invalid value for the preference type.";
                }
            }
            else
            {
                 ViewBag.errormessage = setBlogLikeOrDisLikeResult.ApiErrorMessage;
            }
        }
        catch (Exception ex1)
        {
            exceptionMessage = "Server error on setting the blog like count. Please contact the administrator.";

            try
            {
                ...
            }
            catch (Exception ex2)
            {
                ...
            }
        }

        // Return the partial view with the view model.
        // - This will contain valid data, an error or a web api error message.            
        return PartialView("~/Views/BlogPublished/_BlogLikeAndDislike.cshtml", likeOrDislikeVM);
    }
1 Answers

In short: use text() but not val() when you want to change the content of a <span>.

So this is your js code:

function SetLikeCount(count) {
  // For testing:
  console.log('Here at SetLikeCount. ' + count);
  $(".likeCount").val(count);
}

And this is the corresponding html:

<span class="my-size, likeCount"> : @Model.LikeCount </span>

If you can get the correct count in console.log() but not in .val() function, that's the problem of the .val() function. Not your API calls.

The official documentation from jQuery states when to use val():

The .val() method is primarily used to get the values of form elements such as input, select and textarea. When called on an empty collection, it returns undefined.

Since you call val() in a span element, nothing will be changed.

Instead, you should use text() or html(). For example:

$(".likeCount").text(count);

Good luck!

Related