So here is the problem i’m running into.
Originally, I was populating the recipient field with a select list of users that one would have friended first.
That didn’t seem user friendly enough to me. So, I started working on an autocomplete with jQuery. The autocomplete works like a charm.
The issue i’m running into is when I send the message, my modelstate isn’t valid as the Message. The recipient only has the username filled in.
Should I get rid of the validation and manually fill all these fields?
Or can I do something smarter with this issue?
<div class="label">@Html.LabelFor(model => model.Receiver.UserName)</div>
<div class="fullinput">@Html.TextBoxFor(model => model.Receiver.UserName)</div><br />
<div class="label">@Html.LabelFor(model => model.Subject)</div>
<div class="fullinput">@Html.TextBoxFor(model => model.Subject)</div><br />
<div class="label">@Html.LabelFor(model => model.Content)</div>
<div class="fullinput">@Html.TextAreaFor(model => model.Content)</div><br />
That is the html I’m using.
$("#Receiver_UserName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Function/FindUsers", // Or your controller
dataType: "json",
data: { usr: request.term },
success: function (data) {
// Returned data follows the Spellword model
response($.map(data, function (item) {
return {
id: item.Id,
label: item.UserName,
value: item.UserName
}
}))
}
});
},
This is the autocomplete call:
[HttpPost]
public ActionResult Send(Message message)
{
User user = entities.Users.SingleOrDefault(u => u.UserName.Equals(User.Identity.Name));
//ViewData["Friends"] = new SelectList(user.Friends, "Id", "Name");
if (ModelState.IsValid)
{
entities.Messages.Add(message);
entities.SaveChanges();
return RedirectToAction("Index");
}
return View(message);
}
There I check for the validation, and it’s always invalid which makes sense, I guess.
public class Message
{
[Key]
public int Id { get; set; }
[Required(ErrorMessage = "Subject is required")]
[Display(Name = "Subject")]
public string Subject { get; set; }
[Required(ErrorMessage = "Message is required")]
[Display(Name = "Message")]
public string Content { get; set; }
[Required]
[Display(Name = "Date")]
public DateTime Created { get; set; }
public Boolean Read { get; set; }
[Required(ErrorMessage = "Can't create a message without a user")]
public int SenderId { get; set; }
public virtual User Sender { get; set; }
[Required(ErrorMessage = "Please pick a recipient")]
public int ReceiverId { get; set; }
public virtual User Receiver { get; set; }
}
And finally the Message Model.
Obviously i don’t have fields for all of these so this is why the modelstate is crying at me.
I’m wondering if i can just skip checking modelstate in this case or if i should fix this in a nicer way.
I Solved the issue like this
But i’m not very happy with the solution as it circumvents my entire validation process