使用Ajax将记录添加到数据库

时间:2014-03-25 23:59:32

标签: jquery ajax asp.net-mvc

我正在尝试使用ajax创建聊天客户端。我有一个数据库设置和使用教程的基本信号器聊天客户端设置。我试图让我的数据库工作,但我似乎无法让它进行沟通。

这是我的聊天客户端CSHTML:

@{
    ViewBag.Title = "Chat";
}
<h2>General Chat</h2>

<div id="wrapper">

    <div id="upper-wrapper">
        <div id="available-rooms-dialog">
            <h4>Available Rooms</h4>
            <button type="button" id="createroom" value="Create Room"></button>
        </div>
        <div id="discussion-dialog">
            <textarea rows="30" cols="50" id="discussion"></textarea>
        </div>
    </div>
    <div id="message-dialog">
        <textarea rows="3" id="message">Type your message</textarea>
        <br/>
        <input type="button" id="sendmessage" value="Post" />
        <input type="hidden" id="displayname" />
        <input type="checkbox" id="enter-sends-message"/>
        Enter sends message
    </div>
</div>

@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {

            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.

                //TODO: Add Record to Server
                $('#discussion').append(htmlEncode(name) + " : " + htmlEncode(message) + "\r\n");
            };
            // Get the user name and store it to prepend to messages.
            $('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;

        }

    </script>
}

addmessagetopage函数中有一个TODO语句,我相信我应该添加ajax来将消息添加到服务器。我怎么能这样做呢。我有一个ChatController以及一个消息控制器,我可以使用它来执行该过程。我的消息数据库设置如下:

enter image description here

我可以选择任何其他路线,因为截至目前我很困难。

0 个答案:

没有答案