C#ASP.NET MVC - 模型在POST上被取消

时间:2016-10-29 11:57:34

标签: c# asp.net asp.net-mvc

我已经在这个问题上苦苦挣扎了一段时间,我无法找到任何解决方案来解决这个问题。

我试图在视图中为我的模型添加一个字符串,但是当模型返回到我的HttpPost时,除了我试图填充的字符串外,所有内容都为null

我的模型看起来像这样

namespace WhatsUp.Models {
    public class ChatModel
    {
        public Account user { get; set; }
        public Contact contact { get; set; }
        public Chat chatA { get; set; }
        public Chat chatB { get; set; }
        public string newMessage { get; set; }

        public ChatModel() { }

        public ChatModel(Account user, Contact contact, Chat chatA, Chat chatB)
        {
            this.user = user;
            this.contact = contact;
            this.chatA = chatA;
            this.chatB = chatB;

        }
    }
}

我的控制器看起来像这样

namespace WhatsUp.Controllers
{
    public class ChatsController : Controller
    {
        IMessageRepository repository = new DbMessageRepository();
        IContactRepository contactRepository = new DbContactRepository();
        IAccountRepository accountRepository = new DbAccountRepository();
        IChatRepository chatRepository = new DbChatRepository();

        // GET: Chats
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Chat(int contactId)
        {

            Account user = accountRepository.GetAccount(User.Identity.Name);
            Contact contact = contactRepository.GetContact(contactId);
            Chat chatA = chatRepository.GetChat(user.id, contact.accountId ?? default(int));
            if(chatA == null)
            {
                chatRepository.CreateChat(user.id, contact.accountId ?? default(int));
            }
            Chat chatB = chatRepository.GetChat(contact.accountId ?? default(int), user.id);
            if(chatB == null)
            {
                chatRepository.GetChat(user.id, contact.accountId ?? default (int));
            }
            ChatModel chatModel = new ChatModel(user, contact, chatA, chatB);

            return View(chatModel);
        }

        [HttpPost]
        public ActionResult Chat(ChatModel chatModel)
        {
            repository.SendMessage(new Message(0, chatModel.newMessage, chatModel.chatA.Id));
            ModelState.Clear();
            return View(chatModel);
        }


    }
}

我的观点

@using WhatsUp.Models
@model ChatModel

@{
    ViewBag.Title = "Chat";
}

<h2>Chat with @Model.contact.name</h2>

<div id="chatWindow" style="overflow-y:auto; overflow-x:hidden; height:500px;">    

    <script>
    var element = document.getElementById('chatWindow');
    element.scrollTop = element.offsetHeight
    </script>
</div>


    @using (Html.BeginForm())
    {
        @Html.TextAreaFor(x => x.newMessage, new { @class = "form-control"})
        <input type="submit" value="Send" class="btn btn-primary" />
    }

1 个答案:

答案 0 :(得分:0)

始终使用ViewModel进行此类操作。请按照以下步骤操作:

  • 首先,创建一个包含您的消息和聊天ID的ViewModel
  • 其次,将id s作为视图中的隐藏字段。
  • 最后一件事是,在您的POST操作中,确保在发送邮件之前通过Chat获取每个id个实例。