Button Click不会调用Action

时间:2014-04-04 16:20:01

标签: c# jquery asp.net-mvc

当我单击“发布”按钮时,我想向我的数据库添加一条消息,但现在它无法正常工作。单击按钮时没有任何操作,我的Home Conroller中的AddMessage方法永远不会被调用。你碰巧知道为什么吗?

聊天视图:

@{
    ViewBag.Title = "Chat";
}
<h2 id="current-chat">General Chat</h2>

<div id="wrapper">

    <div id="upper-wrapper">
        <div id="available-rooms-dialog">
        </div>
        <div id="add-delete-room">
            <input type="button" onclick="GetRoomName()" id="createroom" value="Create Room" />
            <input type="button" onclick="DeleteRoom()" id="deleteroom" value="Delete Room" />
            <form id="ava-rooms">                
            </form>
        </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" />
    </div>
</div>
@section scripts
    {
    <script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
    <script type="text/javascript">
    var json;
    var currentRoomId;


    setInterval(LoadRoomMessages(currentRoomId), 6000);

    $(function () {
        LoadRooms();
        // 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.

            //===========================================================
            //===================THIS LINE DIDNT DO SHIT=================
            $.ajax(
            {
                type: "Get",
                url: "@Url.Action("GetCurrentRoomId","Home")",
                success: function (data) {
                    currentRoomId = data;
                }

            });
            //==========================================================


            //TODO: Add Record to Server
            $.ajax(
            {
                type: "Post",
                url: "@Url.Action("AddMessage", "Home")",
                data: { messageCont: message.toString() },
                success: function (data) {
                    LoadRoomMessages(currentRoomId);
                }
            });


        };

        //$('#sendmessage').click(AddMessage());
        // Get the user name and store it to prepend to messages.
        // 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();
            });
        });
    });

        @*function AddMessage() {
            $.ajax(
{
    type: "Post",
    url: "@Url.Action("AddMessage", "Home")",
                data: { messageCont: message.toString() },
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    //access with data[i].modelattribute
                    LoadRoomMessages(currentRoomId);
                }
            }
        });

        }*@
    // This optional function html-encodes messages for display in the page.
    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;

    }

    function GetRoomName() {
        var newRoomName = prompt('Enter a new Room Name', 'Name');
        $.ajax(
        {
            type: "Post",
            url: "@Url.Action("AddRoom", "Home")",
            data: { chatRoom: newRoomName },
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    //access with data[i].modelattribute
                }
                $('#ava-rooms').empty();
                LoadRooms();
            }
        });
    }

    function DeleteRoom() {
        var roomname = prompt('Enter a Room Name to be Deleted', 'Room Name');
        $.ajax(
        {
            type: "Post",
            url: "@Url.Action("DeleteRoom", "Home")",
            data: { chatRoom: roomname },
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    //access with data[i].modelattribute
                }
                $('#ava-rooms').empty();
                LoadRooms();
            }
        });
    }

    function LoadRooms() {

        $.ajax(
        {
            type: "Get",
            url: "@Url.Action("GetRooms", "Home")",
            success: function (data) {
                json = data;
                var obj = JSON.parse(json);
                GetUserPicture();
                for (var i = 0; i < data.length; i++) {
                    //access with data[i].modelattribute
                    // Add an Onlick event to this statment that calls LoadRoomMessages
                    //onclick="GetRoomName()"
                    $('#ava-rooms').append("<input type=\"button\" " + "onclick=LoadRoomMessages(" + obj[i].Id + ") " + "id=\"" + obj[i].RoomName + "\"" + "value=\"" + obj[i].RoomName + "\" />");
                }

            }
        });

    }

    function GetUserPicture() {
        $.ajax(
    {
        type: "Get",
        url: "@Url.Action("GetUserPicture", "Home")",
        success: function (data) {
            $('.body-content').css("background-image", "url(\"" + data + "\")");

        }
    });

    }

    function LoadRoomMessages(id) {
        $.ajax(
        {
            type: "Get",
            url: "@Url.Action("GetMessages", "Home")",
            data: { roomId: id },
            success: function (data) {
                $('#discussion').empty();
                json = data;
                var obj = JSON.parse(json);
                for (var i = 0; i < data.length; i++) {
                    $('#discussion').append(htmlEncode(obj[i].Author) + " : " + htmlEncode(obj[i].Message) + "\r\n");
                }

            }
        });
    }

</script>
}

家庭控制器:

using System;
using System.Linq;
using System.Net.NetworkInformation;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using SignalRChat.Models;

namespace SignalRChat.Controllers
{
    public class HomeController : Controller
    {

        ChatDBEntities DB = new ChatDBEntities();
        ChatDBEntities1 DB_Uno = new ChatDBEntities1();
        ChatDBEntities2 DB_Dos = new ChatDBEntities2();


        public ActionResult Chat()
        {

            return View();
        }

        public ActionResult Users()
        {
            return View();
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpGet]
        public string GetUserPicture()
        {
            try
            {
                var authorId = (int)Session["currentUserId"];
                var pic = DB_Dos.ChatRoomUsers.Find(authorId).PictureURL;
                if (String.IsNullOrWhiteSpace(pic))
                    return "http://www.adventuredogblog.com/wp-content/uploads/2014/03/3.jpg";
                else
                {
                    return pic;
                }
            }
            catch (Exception)
            {

                return "http://www.adventuredogblog.com/wp-content/uploads/2014/03/3.jpg";
            }
        }

        [HttpPost]
        public bool AddMessage(string messageCont)
        {
            var authorId = (int) Session["currentUserId"];
            var message = new ChatMessage();
            message.Author = DB_Dos.ChatRoomUsers.Find(authorId).UserName; // Add Code to get the actual user
            message.AuthorId = authorId; ; //Add Code to get current user Id
            message.Message = messageCont;
            message.MessageDate = DateTime.UtcNow;
            message.RoomId = (int)Session["currentRoomId"]; ; //Add Room Code
            message.RoomName = DB_Uno.ChatRooms.Find(message.RoomId).RoomName; // Get actual name based on id

            try
            {
                DB.ChatMessages.Add(message);
                DB.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        [HttpGet]
        public int GetCurrentRoomId()
        {
            return (int) Session["currentRoomId"];
        }

        [HttpGet]
        public string GetMessages(int roomId)
        {
            Session["currentRoomId"] = roomId; 
            var messages = (from message in DB.ChatMessages where message.RoomId == roomId orderby message.MessageDate ascending select message).ToList();
            var serializer = new JavaScriptSerializer();
            string json = serializer.Serialize(messages);
            return json;
        }

        [HttpPost]
        public bool AddRoom(string chatRoom)
        {
            var room = new ChatRoom();

            room.IsActiveRoom = true;
            room.RoomName = chatRoom;
            room.isDefaultRoom = false;
            room.UserCount = 1;
            room.Id = -1;
            try
            {
                DB_Uno.ChatRooms.Add(room);       
                DB_Uno.SaveChanges();
                return true;
            }
            catch (Exception)
            {
               return false;
            }  
        }

        [HttpPost]
        public bool DeleteRoom(string chatRoom)
        {
            var userId = (from u in DB_Uno.ChatRooms where u.RoomName == chatRoom select u.Id).ToList()[0];
            var room = DB_Uno.ChatRooms.Find(userId);
            var messages = (from u in DB.ChatMessages where u.RoomId == room.Id select u).ToList();
            try
            {
                foreach (var message in messages)
                {
                    DB.ChatMessages.Remove(message);
                }
                DB.SaveChanges();
                DB_Uno.ChatRooms.Remove(room);
                DB_Uno.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        [HttpGet]
        public string GetRooms()
        {
            var rooms = DB_Uno.ChatRooms;
            var serializer = new JavaScriptSerializer();
            string json = serializer.Serialize(rooms);
            return json;
        }

        public ActionResult AddUser()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddUser(ChatRoomUser user)
        {
            var users = DB_Dos.ChatRoomUsers;

            try
            {
                user.LastActivity = DateTime.UtcNow;
                user.RoomId = 1;
                user.RoomName = "General Chat";
                users.Add(user);
                DB_Dos.SaveChanges();
                Session["currentUserId"] = user.UserId;
                return View("Chat");
            }
            catch(Exception)
            {
                return View();
            }
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(ChatRoomUser LUser)
        {
            var userId = (from u in DB_Dos.ChatRoomUsers where u.UserName == LUser.UserName select u.UserId).ToList();
            var user = DB_Dos.ChatRoomUsers.Find(userId[0]);
            if(user.password == LUser.password)
            {
                user.LastActivity = DateTime.UtcNow;
                Session["currentRoomId"] = user.RoomId;
                Session["currentUserId"] = user.UserId;
                DB_Dos.SaveChanges();
                return View("Chat");
            }
            else
            {
                return View();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使用表单action attribute将其指向您的控制器或使用即{。{}}并将您的按钮放在表单中