我已经在这个问题上苦苦挣扎了一段时间,我无法找到任何解决方案来解决这个问题。
我试图在视图中为我的模型添加一个字符串,但是当模型返回到我的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" />
}
答案 0 :(得分:0)
始终使用ViewModel进行此类操作。请按照以下步骤操作:
ViewModel
。 id
s作为视图中的隐藏字段。 Chat
获取每个id
个实例。