I have created the following view for users to create new items. Ive tried to create a bit of validation so if the user leaves a field blank, then it produces a validation message. However, if the user does leave a field blank, my application crashes on the following line: _headline = structuralObject.SetValidValue(value, false) in the Model.Designer.cs file. because:
This property cannot be set to a null value.
Part of my Model.Designer.cs file:
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String headline
{
get
{
return _headline;
}
set
{
OnheadlineChanging(value);
ReportPropertyChanging("headline");
_headline = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("headline");
OnheadlineChanged();
}
}
The section of code this applies to is as follows in my Create View:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>News Details</legend>
<br />
Posted Date:
<div class="editor-field">
@Html.EditorFor(model => model.posted)
@Html.ValidationMessageFor(model => model.posted)
</div>
<br />
Headline Title:
<div class="editor-field">
@Html.EditorFor(model => model.headline)
@Html.ValidationMessageFor(model => model.headline)
</div>
<br />
The following is my AccountModels.cs file where i entered the validation for the View:
[MetadataType(typeof(NewsValidation))]
public partial class News
{
}
public class NewsValidation
{
[Required(ErrorMessage = "Posted date is required")]
public DateTime posted { get; set; }
[Required(ErrorMessage = "Headline is required")]
[Display(Name = "Headline")]
public string headline { get; set; }
[Required(ErrorMessage = "Story body is required")]
public string story { get; set; }
}
I was told it was because my database allowed Null values however since then i have created a new database which no longer allows Nulls. My application still crashes and dont know where to start. Here’s the odd thing, when it crashes, i click play for it to continue, and the validation appears. So it looks like the validation works but for some reason by application crashes beforehand.
Can anyone offer any support?
The problem is that the setter of the
headlineproperty on your domain model is attempting to perform the update. This setter is invoked by the default model binder when it attempts to bind the action argument from the request. And if the user leaves the headlines field blank you will get this exception.I would very strongly recommend you using view models and never passing your domain models to the view. So define a simple NewsViewModel:
and then have your controller action pass it to the view:
and obviously the view will be now strongly typed to your view model: