如何使此ASP.NET核心模型验证在客户端工作? [英] How to make this ASP.NET Core Model Validation work on client-side?

查看:73
本文介绍了如何使此ASP.NET核心模型验证在客户端工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET Core 1.1.1应用程序中,以下模型验证不起作用.我认为该问题与我在下面的主视图"中未正确添加验证脚本有关.

In my ASP.NET Core 1.1.1 app the following Model Validation is not working. I think the issue is related to me not properly adding validation scripts in Main View below.

场景:

  1. 我在主视图上单击一个调用partial view的按钮.
  2. 我在部分视图中输入所有正确的值,然后提交表单(在部分视图中),提交表单successfully并将所有值正确输入到SQL Server数据库中.
  3. 然后,我intentionallyprice(即nullable type float的)输入框中输入一个字符串,例如abc,然后提交表单.甚至不会出现客户端错误(在我的Chrome浏览器中启用了javascript).因此,Form被提交到服务器,而在POST操作方法中,ModeState.IsValid预期为false.
  1. I click on a button on Main View that calls a partial view.
  2. I enter all correct values, in partial view and submit the form (in partial view), the form successfully gets submitted and all the values are correctly entered into SQL server db.
  3. I then intentionally enter a string, say, abc into the input box for price (that is of nullable type float) and submit the form. A client side error does NOT show up even (the javascript is enabled on my Chrome browser). Hence, Form gets submitted to the server where ModeState.IsValid, as expected, is false in the POST action method.

问题:为什么上面的客户端验证(如步骤3所示)不起作用,以及如何使其起作用?

Question: Why client-side validation (as shown in step 3) above is not working and how we can make it work?

注意:创建项目时,VS2017默认情况下已添加并配置了所有css和javascript.因此,我认为脚本无所不在,我可能无法在视图上正确调用它们-但这只是一个假设.

Note: All the css and javascripts were added and configured by default by VS2017 when the project was created. So I think scripts are all there and I may not be calling them correctly on the views - but that's just an assumption.

MyViewModel

public class MyViewModel
{
    public int FY { get; set; } 
    public byte OrderType { get; set; }
    public float? Price { get; set; } 
    ....
}

主视图

@model MyProj.Models.MainViewModel

...
<div>
  <button type="submit" name="submit"...>GO</button>
</div
@section scripts
{
  <script>
    $(document).ready(function () {
     ....
     $('.tab-content').on('click', '.BtnGO', function (event) {
    ....    
    $.ajax({
        url: '@Url.Action("SU_AddCustOrder", "MyContr")',
        data: { ....},
        contentType: 'application/json',
        dataType: 'html',
        type: 'GET',
        cache: false,
        success: function (data) {
            if (BtnVal == 'AddOrderBtnGo')
                $('#menuAP').html(data);
            else if ....
        error: function (....){
              alert(...);
        }
    });
});

MyContrController :

[HttpGet]
public IActionResult AddCustOrder(int Order_id)
{
 ....
 return PartialView("~/Views/PartialsV/MyPartialView.cshtml", myVM);
 ....
}

[HttpPost]
public IActionResult AddCustOrder(MyViewModel model)
{
 ....
 if(ModelState.IsValid)
 {
   ....
 }
 ....
}

局部视图

....
<div class="form-group">
    <label asp-for="Price"></label>
    <div class="col-md-10">
        <input asp-for="Price" class="form-control"></input>
        <span asp-validation-for="Price" class="text-danger"></span>
    </div>
</div>
....
<button type="submit" name="submit"...>Add Order</button>

更新

_layout.cshtm 文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - Test</title>

    <environment names="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment names="Staging,Production">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
    @RenderSection("styles", required:false)
</head>
<body>
    <header>
        <div class="container navbar navbar-inverse navbar-fixed-top text-center">
        </div>
        <div class="container nav nav-pills" style="margin-top:4px;background-color:cornsilk;">
            @await Component.InvokeAsync("Welcome")
        </div>
    </header>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer class="text-center">
            <a asp-controller="Misc" asp-action="AccessibilityStatement" class="text-center text-muted">Accessibility Statement</a>
        </footer>
    </div>

    <environment names="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment names="Staging,Production">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("scripts", required: false)
    @RenderSection("css", required:false)
</body>
</html>

推荐答案

我明白了.如果您打开Views文件夹内的Shared文件夹,则会找到一个名为_ValidationScriptsPartial.cshtml的文件,其中包含验证脚本.

I see. If you go and open Shared folder inside Views folder you will find a file called _ValidationScriptsPartial.cshtml that contains the validation scripts.

现在要做的第一件事就是将验证属性(例如[Required])添加到视图模型.

Now the first thing to do is to add validation attributes such as [Required] to your view model.

主视图中之前,在<script>之前添加@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }.

在此行$('#menuAP').html(data);中添加部分视图的html之后,找到表单并按如下所示调用$.validator.unobtrusive.parse()

After you add the html of the partial view in this line $('#menuAP').html(data);, find the form and call $.validator.unobtrusive.parse() like the following

if (BtnVal == 'AddOrderBtnGo') {
   $('#menuAP').html(data);
   var $form = $('#menuAP').find('#your-form-id-here');
   $.validator.unobtrusive.parse($form);
}

这篇关于如何使此ASP.NET核心模型验证在客户端工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆