Asp.net Core中带有Ajax的验证表 [英] Validation Form With Ajax in Asp.net Core

查看:112
本文介绍了Asp.net Core中带有Ajax的验证表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AJAX将表单发送到ASP.NET Core中的控制器,但是我无法通过验证发送表单

I use AJAX to send forms to controller in ASP.NET Core but I have problem with send form with validation

<form asp-action="Create" asp-controller="Departments"
      data-ajax="true"
      data-ajax-method="Post"
      data-ajax-mode="replace"
      data-ajax-update="#content"                 
      data-ajax-success="Success"
      data-ajax-failure="Failure">
    <div class="box-body">
       <div class="alert alert-success" id="divalert" ></div>

        <div class="form-group">
            <label asp-for="Title" class="control-label"></label>
            <input asp-for="Title" class="form-control" />
            <span asp-validation-for="Title" class="text-danger"></span>
        </div>
        <div class="form-group">
            <input type="submit" value="ثبت" class="btn btn-success" />
        </div>
    </div>
</form>

这是Ajax的Jquery代码

This is Jquery code For Ajax

<script>
    function Success() {
        $("#divalert").text = "Yes";
    }
    function Failure() {
        $("#divalert").text = "No";

    }

</script>

但是我想在发送带有空文本框的表单时显示验证消息,

but I want to show validation message ehen I send form with empty text Box ,

这是我的控制器

public async Task<IActionResult> Create([Bind("Department_Id,Title,Task,Description,Department_Status")] Department department)
{
    if (ModelState.IsValid)
    {             
        _genericRepository.Add(department);
        await _genericRepository.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(department);
}

当表单为空时,如何在Ajax中显示验证消息?

How do I show validation message with Ajax when form is empty ?

推荐答案

我使用局部视图创建"并且有效

I use partial view "Create" and it works

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<div class="form-horizontal">
    <form asp-action="Create" role="form" asp-controller="Department" asp-antiforgery="true"
          data-ajax-success="Bindgrid"
          data-ajax="true"
          data-ajax-method="POST">
        <div class="form-group">
            <label class="control-label" asp-for="DepartmentName"></label>
            <input class="form-control" type="text" asp-for="DepartmentName" />
            <span asp-validation-for="DepartmentName" class="text-danger"></span>
        </div>
        <input class="btn btn-primary" type="submit" value="Save" />
    </form>
</div>

所有jquery文件都需要html或ajax验证.

all jquery file is needed for html or ajax validation.

这篇关于Asp.net Core中带有Ajax的验证表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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