Optional validation for MVC fields

I am creating a new MVC site, because that is what the cool kids are doing these days. On my entry page, all the fields were required, and I had a couple of them that I didn’t want to be required. So I went into my view and found the fields:

<div>
@Html.LabelFor(model => model.Latitude)
</div>
<div>
@Html.EditorFor(model => model.Latitude)
@Html.ValidationMessageFor(model => model.Latitude)
</div>

<div>
@Html.LabelFor(model => model.Longitude)
</div>
<div>
@Html.EditorFor(model => model.Longitude)
@Html.ValidationMessageFor(model => model.Longitude)
</div>

Easy, I’ll just remove the Html.ValidationMessageFor control, and it will be fine. Nope, that didn’t work – the validation message disappeared, but the page wouldn’t let me save. I also tried eating Cheez-Its, because they always make me feel better. While they did make me feel better, I was still having a problem.

What I found that did work was making the fields in question nullable. I went into my model and found the fields I wanted to be optional:

public double Latitude { get; set; }
public double Longitude { get; set; }

Through the magic of question marks, I made them nullable:

public double? Latitude { get; set; }
public double? Longitude { get; set; }

And there I was, with two fields that were no longer required. If there is a better / easier / different way, add a comment and let me know.

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: