向Controller发送请求并获取结果并在MVC中的View上显示 [英] Send a request to a Controller and get result and show on View in MVC

查看:120
本文介绍了向Controller发送请求并获取结果并在MVC中的View上显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好吧



我有一个控制器来计算评论的喜欢和不喜欢的数量。

我的控制器是:

Hi every body

I have a controller for counting number of Like and Dislike of a comment.
My controller is:

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:

<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>





我如何发送请求(例如通过$ .ajax)得到结果并显示在视图中??



请帮助我



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

Please help me

推荐答案

.ajax)并获得结果并显示在视图中??



请帮帮我
.ajax) and get result and show that in view??

Please help me


最重要的是将Jquery包含在你的项目和下面的内容应该对var名称进行修改。



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

var getLikeCount= function (ID) {


.ajax({
url:' @ Url.Ac (注意,赞)'
类型:' POST'
数据:{ ID:ID},
dataType:' json'
成功:功能(响应){
alert(data.likeCount);
},
错误: function (错误){
alert(error);
}
});};

< input type = button class = Note-Like-Imageönclick= like(@ item.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)"/>


这篇关于向Controller发送请求并获取结果并在MVC中的View上显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆