Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi every body

I have a controller for counting number of Like and Dislike of a comment.
My controller is:
C#
public int Like(long commentId)
{
    Entities entity = new Entities();
    Note note = entity.Notes.SingleOrDefault(a => a.ID == id);
    string user = Request.UserHostAddress;
    bool exist = false;

    foreach (NoteUserAddress item in entity.NoteUserAddresses.Where(a => a.NoteID == commentId))
        if (item.UserAddress == user)
            exist = true;

    if (exist == false)
    {
        note.LikeCount++;
        entity.SaveChanges();
    }
    return note.LikeCount;
}


My view is:
HTML
<input type="button" class="Note-Like-Image" onclick="like(@item.ID)"/>
<div class="Note-Like-Count" id="NoteLikeCounter">@item.LikeCount</div>

<script type="application/javascript">
function like(id) {
    //I can make my controller and action address
    // Now I want to send a request to Like action and get result and show that in NoteLikeCounter
}
</script>
    </script>


How I can sent a request (for example by $.ajax) and get result and show that in view??

Please help me
Posted
Comments
ALLAMI Said 18-Apr-14 10:58am    
you should use a partial view to return the information that you need
Reza Alipour Fard 18-Apr-14 11:12am    
I want to only a number. I think using partial view for this problem isn't good solution.
I want send an ajax request to controller and get result and use that in view.

Most importantly include Jquery into your project and the below should work with modifications to the var names.

JavaScript
var getLikeCount= function (ID) {$.ajax({
        url: '@Url.Action("Note", "Like")',
        type: 'POST',
        data: { "ID": ID },
        dataType: 'json',
        success: function (response) {
            alert(data.likeCount);
        },
        error: function (error) {
            alert(error);
        }
    });};

<input type="button" class="Note-Like-Image"  önclick="like(@item.ID)"/>
 
Share this answer
 
v2
Comments
Reza Alipour Fard 19-Apr-14 3:16am    
It doesn't work correctly. I have an error.
Please tell me full information about this problem.
Please try is as below.

Action Method

SQL
[HttpGet]
public JsonResult int Like(long commentId)
{
    //your code goes here

    return Json(new { LikeCount = note.LikeCount },JsonRequestBehavior.AllowGet);
}



Javascript

//JS closure enabled function
var likeCountFunction = function () {

            $.ajax({
                url: "/Your-Controller/Like",
                type: 'Get',
                dataType: "json",
                cache: false,
                data: { commentId: commentId},
                success: function (data) {

                    alert(data.LikeCount)

                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {

                    alert('error')
                }
            });
        };

  likeCountFunction();//call your function
 
Share this answer
 
v4
Comments
Reza Alipour Fard 18-Apr-14 11:22am    
Thank you for your attention.
Your java script has some syntax error.
Please check it.
Thanks a lot.
Sampath Lokuge 18-Apr-14 11:24am    
Just correct it and use.I gave only the path for your task. :)
Reza Alipour Fard 18-Apr-14 11:34am    
How are your Sampath. sorry first time I couldn't remember you.
You are one of my friends in Linked In.
I tried to use this format of ajax request many times today, but I get bellow error all the time:

"3:92Uncaught TypeError: Cannot call method 'ajax' of undefined ", pLEASE HELP ME.
Sampath Lokuge 18-Apr-14 11:37am    
Can you put your code snippet which you use (JS)?
Reza Alipour Fard 18-Apr-14 11:37am    
<script type="application/javascript">
function like(id) {
$.ajax({
url: "/Note/Like",
type: 'Get',
dataType: "json",
cache: false,
data: { commentId: id},
success: function (data) {

alert(data.LikeCount)

},
error: function () {
alert("error");
}
});

};
</script>
try with this javascript code

JavaScript
$.ajax({
        url: '@Url.Action("YourAction", "YourController")',
        type: 'POST',
        data: { "ID": ID },
        dataType: 'json',
        success: function (response) {
            alert(response);
        },
        error: function (error) {
            alert(error);
        }
    });


Good luck
 
Share this answer
 
Comments
Reza Alipour Fard 18-Apr-14 11:36am    
I get bellow error:
"3:92Uncaught TypeError: Cannot call method 'ajax' of undefined "
Hi Every Body

I solved my problem with bellow solution:

JavaScript Part:
JavaScript
<script>
    function Like(ID)
    {
        var xmlhttp;
        var pageurl = "/Note/Like/" + ID
        if (window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest();
        }
        else
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.getElementById("NoteLikeCounter").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET",pageurl,true);
        xmlhttp.send();
    }
</script>


Controller Part:
C#
public int Like(long id)
{
    FaezEntities entity = new FaezEntities();
    Note note = entity.Notes.SingleOrDefault(a => a.ID == id);
    string user = Request.UserHostAddress;
    bool exist = false;

    foreach (NoteUserAddress item in entity.NoteUserAddresses.Where(a => a.NoteID == id))
        if (item.UserAddress == user)
            exist = true;

    if (exist == false)
    {
        note.LikeCount++;
        entity.SaveChanges();
    }

    return note.LikeCount;
}


View Part:
HTML
<input type="button" class="Note-Like-Image"  önclick="Like(@item.ID)" />


Thank you for your attention specially Thank you "Sampath Lokuge".
I hope this solution can help you.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900