0

I have a simple ViewModel

public class ProductViewModel
{
    [Required(ErrorMessage = "This title field is required")]
    public string Title { get; set; }
    public double Price { get; set; }
}

here's my form based on this View Model.

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>ProductViewModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Title)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Title)
        @Html.ValidationMessageFor(model => model.Title)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Price)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Price)
        @Html.ValidationMessageFor(model => model.Price)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

}

I dont want to validate the price field. but it got automatically validated, if nothing entered, will show this field is required. I notice I use double for price. If I changed it to "string". validation is removed. why type "double" cause automatic validation?

2 Answers 2

1

I dont want to validate the price field. but it got automatically validated, if nothing entered, will show this field is required

Because a double is a value type, which cannot be null. If you want the value to allow not having a value, use a nullable double: double? on your model:

public class ProductViewModel
{
    [Required(ErrorMessage = "This title field is required")]
    public string Title { get; set; }
    public double? Price { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Because double is a value type, and cannot be null. You could have made it double? or Nullable<double> and it would be fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.