跟踪 C# 控制器和视图中的两个变量

本文关键字:两个 变量 控制器 视图 跟踪 | 更新日期: 2023-09-27 17:56:04

我的控制器类中有两个变量,第一个称为currentUserId,它意味着存储登录到网站的当前用户。第二个变量是 currentRoomId,用于跟踪用户所在的当前聊天室。问题是,当用户登录时,它将正确的变量很好地存储到两个变量中,但是在它离开范围后,它不会保存值。我需要做的基本事情是跟踪这两个变量。我不确定最好的方法是什么。

这是我目前拥有的:

我的控制器:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using Microsoft.Ajax.Utilities;
using SignalRChat.Models;
using System.Web;
namespace SignalRChat.Controllers
{
    public class HomeController : Controller
    {
        ChatDBEntities DB = new ChatDBEntities();
        ChatDBEntities1 DB_Uno = new ChatDBEntities1();
        ChatDBEntities2 DB_Dos = new ChatDBEntities2();
        int currentUserId = -1;
        int currentRoomId = 1;
        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();
        }
        [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(currentRoomId).RoomName; // Get actual name based on id
            try
            {
                DB.ChatMessages.Add(message);
                DB.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        [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;
        }
        [HttpGet]
        public int GetCurrentRoomId()
        {
            return currentRoomId;
        }
        [HttpGet]
        public int GetCurrentUserId()
        {
            return currentUserId;
        }
        [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;
            }  
        }
        [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();
                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)
            {
                currentUserId = user.UserId;
                user.LastActivity = DateTime.UtcNow;
                Session["currentRoomId"] = user.RoomId;
                Session["currendUserId"] = user.UserId;
                DB_Dos.SaveChanges();
                return View("Chat");
            }
            else
            {
                return View();
            }
        }
    }
}

以下是我的观点:

@{
    ViewBag.Title = "Chat";
}
<h2>General Chat</h2>
<div id="wrapper">
    <div id="upper-wrapper">
        <div id="available-rooms-dialog">
            <h4>Available Rooms</h4>
        </div>
        <form id="ava-rooms">
            <input type="button" onclick="GetRoomName()" id=" createroom" value="Create Room" />
        </form>
        <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 src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script type="text/javascript">
    var json;
    var currentUserId;
    var CurrentRoomId;
    var MyVariable = '@ViewBag.MyVariable';

    $(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.
            $.ajax(
            {
                type: "Get",
                url: "@Url.Action("GetCurrentRoomId", "Home")",
                success: function (data)
                {
                    currentRoomId = data;
                }
            });
            $.ajax(
            {
                type: "Get",
                url: "@Url.Action("GetCurrentUserId", "Home")",
                success: function (data)
                {
                    currentUserId = data;
                }
            });
            //TODO: Add Record to Server
            $.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
                    }
                }
            });
            $.ajax(
            {
                type: "Get",
                url: "@Url.Action("GetMessages", "Home")",
                success: function (data) {
                    json = data;
                    var obj = JSON.parse(json);
                    for (var i = 0; i < data.length; i++) {
                        //access with data[i].modelattribute
                        $('#discussion').append(htmlEncode(obj[i].Author) + " : " + htmlEncode(obj[i].Message) + "'r'n");
                    }
                }
            });
        };
        // 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();
            });
        });
    });
    // 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
                }
            }
        });
    }
        function LoadRooms() {
           $.ajax(
           {
               type: "Get",
               url: "@Url.Action("GetRooms", "Home")",
                success: function (data) {
                    json = data;
                    var obj = JSON.parse(json);
                    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 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>
}
}

有什么建议吗?

跟踪 C# 控制器和视图中的两个变量

您可以使用

Session来存储这些变量。只要会话未过期,它们将在任何控制器或视图上使用。

在控制器上设置会话变量

Session["currentRoomId"]  = roomId;

获取控制器上的会话变量

int roomId = (int)Session["currentRoomId"];

获取剃刀视图上的会话变量

@Session["currentRoomId"]