Broodstok Broodstok - 1 month ago 6
ASP.NET (C#) Question

C# ASP.NET MVC - Model gets nulled on POST

I've been struggling with this problem for a while now and I can't find any solution on that solves it for me.

I'm trying to add a string to my model in a view, however when the model gets returned to my HttpPost everything is null except for the string that I'm trying to fill

My model looks like this

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;

}
}
}


My controller looks like this

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);
}


}
}


And my view

@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" />
}

Answer

Always use a ViewModel for that kind of things. Follow this steps:

  • First, create a ViewModel that will contain your message and the chat ids.
  • Second, ake the ids as a hidden field in your view.
  • Last thing is, in your POST action, to make sure to get each Chat instance via their id before sending the message.
Comments