× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

mvc insert cannot be null error in entity framework

Praveen Paulose
Apr 20, 2015
<p>Since you are picking this up from User.Identity.Name, you can assign it in the HttpPost method.</p> <pre><code>[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Post post) { post.BlogUserEmail = User.Identity.Name try { if (ModelState.IsValid) { db.Posts.Add(post); db.SaveChanges(); return RedirectToAction("Index"); } var email = User.Identity.Name; ViewBag.BlogUserEmail = new SelectList(db.BlogUsers, email); ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", post.CategoryId); return View(post); } catch (DbEntityValidationException e) { var newException = new FormattedDbEntityValidationException(e); throw newException; } } </code></pre> <p>Since it is not an editable field in the Create View, you can also take an approach of putting in a HiddenField. </p> <p>Remember that readonly labels will not bind to your model in the Post method.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/29722294/mvc%20insert%20cannot%20be%20null%20error%20in%20entity%20framework/29722357">Stack Overflow</a>.</p>
comments powered by Disqus