Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Optional Model Property

I have a dropdownlist which I would like to be optional, however, the ModelState.IsValid check is trying to validate the property. Is there a way to tell it the property is optional?

Here is my code:

<h2>New Version</h2>

@using (Html.BeginForm()) {
    <div>Version Number: @Html.TextBoxFor(m => m.Number)</div>
    <div>Enabled: @Html.CheckBoxFor(m => m.IsActive)</div>

    <div></div>

    <div>
        Template (optional): 
        @Html.DropDownListFor(m => m.TemplateVersionId, new SelectList(Model.CurrentVersions, "VersionId", "Number"),
            "-- Select Template --")
    </div>

    <input type="submit" value="Save" />
    @Html.ActionLink("Cancel", "Index");
}

and my ViewModel:

public class AddVersionViewModel
{
    public double Number { get; set; }
    public bool IsActive { get; set; }

    public int TemplateVersionId { get; set; }
    public ICollection<Version> CurrentVersions { get; set; }
}

I want the TemplateVersionId to be optional.

like image 567
shuniar Avatar asked Sep 22 '11 14:09

shuniar


1 Answers

Change it to an int? to make it nullable.

like image 131
SLaks Avatar answered Oct 26 '22 21:10

SLaks