4

Я создал в своем проекте контроллер, используя шаблон MVC Controller with views, using Entity Framework. И когда я попытался добавить в свою БД дробные числа (например, 77.9), то выдало на экран:

Значением поля RotationSun должно быть число

и

77.9 не является допустимым значением для RotationSun

Я пробовал вводить числа не с точкой, а с запятой, тот же результат. В БД такие строки не добавляются. Если что, я использую Code First. Вот все поля моей модели Comet:

    public int CometId { get; set; }

    public double? Volume { get; set; }

    public double? Weight { get; set; }

    public decimal DistanceEarth { get; set; }
    public decimal DistanceSun { get; set; }
    public double RotationSun { get; set; }

    public string Name { get; set; }
    public string Description { get; set; }
    public string CimageURL { get; set; }

Кстати говоря, то же самое происходит и с полями типа decimal, и с полями типа double.

Вот мое представление Create.cshtml из папки Comets:

  @model SolarSystemWithViews.Models.Comet


   @{
    ViewBag.Title = "Create";
    }

    <h2>Create</h2>


       @using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) 
      {
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Comet</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Volume, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Volume, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Volume, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Weight, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Weight, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Weight, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DistanceEarth, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DistanceEarth, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DistanceEarth, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DistanceSun, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DistanceSun, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.DistanceSun, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.RotationSun, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.RotationSun, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RotationSun, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CimageURL, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="UploadImage" id="UploadImage">
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
    }

         <div>
             @Html.ActionLink("Back to List", "Index")
          </div>

@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
  }
0

1 ответ 1

3

Вот тут два способа описывалось, я всегда пользовался вариантом 1.

Решение 1

Переопределение валидатора в JavaScript:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script>
    // переопределение валидации на стороне клиента
    $.validator.methods.range = function (value, element, param) {
        var globalizedValue = value.replace(",", ".");
        return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
    }

    $.validator.methods.number = function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
    }
    </script>
}

Решение 2

Переопределение культуры в web.config:

<globalization culture="en-US" uiCulture="en" />

Больше разных вариантов на англ. SO, их там много от русскоязычных участников видел.

Update. Если кому понадобится вариант на asp.net core -- там я почему-то стал использовать вариант с настройкой культуры (уже не помню, чем руководствовался), как-то так:

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var appDefaultCulture = new CultureInfo("ru-RU")
        {
            NumberFormat =
            {
                NumberDecimalSeparator = ".",
            },
        };

        var supportedCultures = new[] { appDefaultCulture };

        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture(appDefaultCulture),
            SupportedCultures = supportedCultures,
            SupportedUICultures = supportedCultures
        });

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.