Reputation: 815
I have view for adding very simple objects:
@Html.ValidationSummary(true)
@using (Html.BeginForm())
{
<div class="editor-label">
@Html.LabelFor(tag => tag.Name)
</div>
<div class="editor-field">
@Html.EditorFor(tag => tag.Name)
@Html.ValidationMessageFor(tag => tag.Name)
</div>
<input type="submit" value="Insert" class="submit_btn" />
}
I made controller like this:
if (ModelState.IsValid)
{
...
context.Tags.Add(Tag);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(Tag);
The model is being generated from database schema (as a part of edmx). Field name nullable property is set to false.
In some way, for blank input "name" the ModelState.IsValid property is true and it's trying to save it (on SaveChanges() it crashes with validation error). Why?
Upvotes: 1
Views: 1673
Reputation: 17594
The IsValid
property of ModelState
does not have anything to do with your entity models. The ModelState
looks at the attributes with which you've decorated your model properties.
For instance:
public class Tag {
[Required]
public string Name { get; set; }
}
It would also be good to note here that using your database entities as models for your MVC project may not be the best idea. Consider using a mapper to map an entity to a model and vice-versa.
Upvotes: 4
Reputation: 2107
You'd have to add a Required attribute to the Property inside a partial class, just "non-nullable" won't do.
Upvotes: 0