1

我有一个非常奇怪的问题

我有一个视图模型:

public class ServiceView
{
    [Required]
    [Display(Name = "Titre de l' annonce")]
    public string NomService { get; set; }

    [Required]
    [Display(Name = "Description")]
    public string DescriptionService { get; set; }

    [Display(Name = "Adresse")]
    public string AdresseService { get; set; }

    [Display(Name = "Le code postal")]
    public int CodePostalService { get; set; }

}

和一个与我的 ViewModel 紧密相关的 View:

@model MeilleurPresta.Models.ViewModel.ServiceView

@{
    ViewBag.Title = "Déposer une offre";
}

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>


<div class="grid_23" id="body">

    <h3 style="padding-left: 50px"> Déposer une offre de Service </h3>

    <div style="margin-left: 50px">
        @using (Html.BeginForm()) {

            @Html.ValidationSummary(true)

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

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

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

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

            <p>
                <input type="submit" value="Create" />
            </p>
        }
    </div>
</div>

我的控制器:

    public ActionResult Index()
    {
        return View();
    }

没什么特别的,但是,当我提交表单时,在客户端验证时,它告诉我该字段:Le code postal 是必需的,但它不在 ViewModel 中。

我检查了 html 源代码,它生成了 data-val-required 类,而在我的 ViewModel 中没有 require 属性。

问题可能来自哪里?

谢谢

4

1 回答 1

1

因为您的 int 不可为空,所以默认情况下将其标记为必需。您可以将 int 设置为 int? 使其可以为空,或者您可以将其添加到您的 application_start 以更改默认行为...

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
于 2012-04-21T03:29:57.510 回答