0

I have a simple message system on my project. I have name property and if my User is in role Admin, I get the name by User.Identity.Name instead of getting it from View and since I made the name property required, ModelState is not being valid when an admin tries to post something.

[HttpPost]
[ValidateAntiForgeryToken]

public ActionResult Create([Bind(Include = "Message,Name,Subject,Receiver")] Talep talep){
   if (User.IsInRole("Admin")){
                talep.Name = User.Identity.Name;
            }
   if (ModelState.IsValid){
            talep.UploadDate = DateTime.Now;
            var usrId = Request.Form["UserId"];
            talep.Receiver = db.Users.Find(usrId).UserName;
            talep.UserId = User.Identity.GetUserId().ToString();
            db.Talep.Add(talep);
            db.SaveChanges();
            return RedirectToAction("Index");
   }
   return View(talep);
}
  • 2
    First set `talep.Name` if required, then [revalidate the model](http://stackoverflow.com/a/7837186/11683). – GSerg Aug 09 '14 at 20:34

1 Answers1

1

To expand on GSerg comment, the DefaultModelBinder adds the error because the property Name is required but is null. Setting the Name property after the binding process does not remove the error so its still invalid. Your options include

  1. Add the Name property to the view so it posts back
  2. Remove the specific error (i.e. ModelState["Name"].Errors.Clear();) when you set the name
  3. Clear all errors and revalidate (i.e ModelState.Clear(); TryValidateModel(crew);)