Asp.net Core中带有Ajax的验证表

时间:2018-07-02 08:29:01

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

我使用AJAX将表单发送到ASP.NET Core中的控制器,但在发送带有验证的表单时遇到问题

<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代码

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

    }

</script>

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

这是我的控制器

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显示验证消息?

2 个答案:

答案 0 :(得分:1)

我使用局部视图“创建”,并且可以使用

<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验证。

答案 1 :(得分:-1)

我使用这种方式并且有效

这是我应该怎么编码的吗?

我将控制器从IActionResult更改为JsonResult。

public async Task<JsonResult> 
Create([Bind("Department_Id,Title,Task,Description,Department_Status")] 
Department department)
    {

        if (ModelState.IsValid)
        {             

            _genericRepository.Add(department);
            await _genericRepository.SaveChangesAsync();
            return Json(department);

        }

        return Json(department);
    }`