shuniar
shuniar

Reputation: 2622

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.

Upvotes: 5

Views: 4920

Answers (2)

Frederiek
Frederiek

Reputation: 1613

When you create Nullable items it becomes optional in forms

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

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

Upvotes: 1

SLaks
SLaks

Reputation: 887449

Change it to an int? to make it nullable.

Upvotes: 13

Related Questions