1

So I'm a bit new to ASP.NET and MVC. I've got an ASP.NET MVC5 application, using Entity Framework 6. I've generated my models from a SQL Server database, and am so far just using the vanilla index/create/details/edit constructs.

In my models, various fields are marked as "Allow Nulls" and others aren't. While creating a new entry, any type that is, say, an int that is left as null is handled nicely by the ModelState.IsValid check and the @Html.ValidationMessageFor messages.

On one entry test, however, I received a DbEntityValidationException. I used the try/catch from this question to find out that it was one of the string (VARCHAR) fields that was left blank.

I am assuming this is because the string class allows nulls, where as int does not (unless declared as Nullable<type> in the model) thus the controller/model doesn't flag it as invalid.

What would be the easiest way to handle this? Is there a way to decorate the string property in the model so it gets checked as well? Or do I need to go as far as attempting to save, catching the exception, and manually handling the validation messages?

Thanks

1 Answer 1

3

It is possible to decorate your property with a Required-attribute. Mvc wil show an error message when the user is posting a form while this property is empty.

public class TestClassModel
{
    [Required]
    public string RequiredString { get; set; }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the quick response and simple answer!
What if RequiredString will be null?
Then there will be an error in the ModelState and if the validation is turned on, the form on the page won't submit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.