You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ajax将消息状态从未读更新为已读

问题修复方案

前端代码修正

$(document).ready(function () {
    // 初始化未读消息容器
    $('#counterBackground').html('');

    // 获取未读消息列表
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/Message/GetMessages",
        traditional: true,
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            // 更新未读消息计数
            $('#counter').html(data.length);

            let messages = '';

            // 循环构建消息列表HTML
            for (let m of data) {
                messages += `
                <ul>
                    <li data-msg-id="${m.messageId}">
                        <a href="javascript:void(0);">
                            <div class="message-avatar">
                                <img src="https://bootdey.com/img/Content/avatar/avatar3.png" alt="">
                            </div>
                            <div class="message-body">
                                <div class="message-body-heading">
                                    <h5>${m.subject}
                                        <span> 
                                            <small class="fa-pull-right">
                                                <time class="timeago" datetime="">${m.createdDate}</time>
                                            </small>
                                        </span>
                                    </h5>
                                </div>
                                <p>${m.body}</p>
                            </div>
                        </a>
                    </li>
                </ul>`;
            }

            // 一次性插入所有消息到DOM
            document.getElementById("messageList").innerHTML = messages;

            // 绑定消息点击事件
            $('#messageList a').on('click', function () {
                const $li = $(this).closest('li');
                const msgId = $li.data('msg-id');

                // 发送标记已读请求
                $.ajax({
                    type: 'POST',
                    dataType: "json",
                    url: "/Message/UpdateMsgStatus",
                    traditional: true,
                    data: { Id: msgId },
                    success: function (result) {
                        if (result && result.isRead === 1) {
                            // 移除当前消息项
                            $li.closest('ul').remove();
                            // 更新未读计数器
                            const currentCount = parseInt($('#counter').text()) - 1;
                            $('#counter').html(currentCount > 0 ? currentCount : 0);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('标记已读失败:', error);
                    }
                });
            });

            console.log(data);
        },
        error: function (xhr, status, error) {
            console.error('获取消息失败:', error);
        }
    });
});

后端Controller代码修正

public JsonResult UpdateMsgStatus(string Id)
{
    var msg = ctx.Messages.Where(m => m.MessageId == Id).FirstOrDefault();
    if (msg != null)
    {
        msg.IsRead = 1;
        ctx.SaveChanges();
    }
    return Json(msg);
}

关键修正点说明

  • DOM构建优化:将消息HTML插入操作移到循环外部,避免重复操作DOM;移除初始冗余的空消息模板。
  • 点击事件绑定:为每个消息锚点绑定点击事件,通过closest('li')定位当前消息项,用data-msg-id存储消息ID。
  • Ajax请求修正:修正请求方法大小写(Type改为type),参数名与后端Action保持一致,添加错误处理逻辑。
  • 前端状态更新:标记已读成功后,立即移除对应消息项,并更新未读计数器。
  • 后端代码精简:移除不必要的msg.MessageId=Id赋值,查询时已通过该ID定位消息。

内容的提问来源于stack exchange,提问作者Katakyie Kofi Poku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:53:17