JavaScript(JQuery)验证不同文化中的数字(小数)和DropDownListFor onchange

时间:2016-05-17 15:41:41

标签: javascript c# jquery asp.net-mvc

我有测试的网络应用程序。

我非常简单的课程:

// GET: MyClasses/Create
public ActionResult Create()
{
    MyClass myClass = new MyClass()
    {
        Name = "First",
        Value = 1
    };

    var Names = new[]{
        new SelectListItem{ Value="First",  Text="First" },
        new SelectListItem{ Value="Second", Text="Second" },
        new SelectListItem{ Value="Third",  Text="Third" },
        };

    ViewBag.Names = new SelectList(Names, "Value", "Text");
    return View(myClass);
}

// POST: MyClasses/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Name,Value")] MyClass myClass, string Action)
{
    if (Action == "Change name")
    {
        myClass.Value = myClass.Name == "First" ? 1 :
                myClass.Name == "Second" ? 2 :
                myClass.Name == "Third" ? 3 :
                0;
        ModelState.Clear();
    }
    else
    if (ModelState.IsValid)
    {
        db.MyClasses.Add(myClass);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    var Names = new[]{
        new SelectListItem{ Value="First",  Text="First" },
        new SelectListItem{ Value="Second", Text="Second" },
        new SelectListItem{ Value="Third",  Text="Third" },
        };

    ViewBag.Names = new SelectList(Names, "Value", "Text");
    return View(myClass);
}

我改变了我的默认控制器:

@using (Html.BeginForm(null, null, FormMethod.Post, new { @id = "MainForm" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>MyClass</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <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.DropDownListFor(model => model.Name, (IEnumerable<SelectListItem>)new SelectList(ViewBag.Names, "Value", "Text", Model.Name), htmlAttributes: new { @class = "form-control", @onchange = "changeName()" })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Value, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Value, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Value, "", new { @class = "text-danger" })
            </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")
    <script>
        function changeName() {
            var input = $("<input>")
                .attr("type", "hidden")
                .attr("name", "Action").val("Change name");
            $('#MainForm').append($(input));
            $('#MainForm').submit();
        }
    </script>
}

我改变了#34;创造&#34;这样看:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("someculture");
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("someculture");
}

我想让这个应用多语言(改变文化)。我为Global.asax.cs添加了一些代码:

$.validator.methods.number = function (value, element) {
    return this.optional(element) ||
        !isNaN(Globalize.parseFloat(value));
}

$(document).ready(function () {
    Globalize.culture('@(System.Threading.Thread.CurrentThread.CurrentCulture.Name)');
});

jQuery.extend(jQuery.validator.methods, {
    range: function (value, element, param) {
        var val = Globalize.parseFloat(value);
        return this.optional(element) || (val >= param[0] && val <= param[1]);
    }
});

当我使用&#34; en&#34;或者其他文化/语言(&#34; someculture&#34;在Global.asax.cs中),DropDownListFor更改值,控制器(异步任务创建)按预期工作。

我的浏览器默认文化/语言是英语。所以当我使用&#34; fr&#34;或其他文化/语言我在&#34;创建&#34; view&#34;字段值必须是数字。&#34;。 要修复此错误,用户可以更改&#34;,&#34;到&#34;。&#34;在&#34;价值&#34;,但它不是解决方案。

要进行数字验证,我添加了我在其他应用中使用的脚本。我把它添加到&#34;创建&#34;查看脚本部分:

<input type="hidden" value="no" id="submitform" />

但添加此脚本后DropDownListFor停止工作。数字验证是​​有效的,DropDownListFor - no。

我的问题是在一个视图中进行一次验证和DropDownList一次的方法吗?或者我的方法是错误的,否则我应该实现这个功能。

更新

我找到了解决方案。

在视图中添加了新输入:

<script>
        function changeName() {
            var input = $("<input>")
                .attr("type", "hidden")
                .attr("name", "Action").val("Change name");
            $('#MainForm').append($(input));
            document.getElementById("submitform").value = "yes";
            $('#MainForm').submit();
        }

        jQuery.extend(jQuery.validator.methods, {
            range: function (value, element, param) {
                var val = Globalize.parseFloat(value);
                return this.optional(element) || (val >= param[0] && val <= param[1]);
            }
        });

        $.validator.methods.number = function (value, element) {
            if (document.getElementById("submitform").value == "yes") {
                document.getElementById("submitform").value = "no";
                document.getElementById("MainForm").submit();
            }
            return this.optional(element) || !isNaN(Globalize.parseFloat(value));
        }

        $(document).ready(function () {
            Globalize.culture('@(System.Threading.Thread.CurrentThread.CurrentCulture.Name)');
        });
    </script>

以这种方式修改脚本:

Range("D" & compteur) = valueLogon & "," &

0 个答案:

没有答案