原文

全文源码

开始项目

项目使用了package.json'文件,添加需要的前端package到项目中。在这我们添加了jquery-ajax-unobstrusive`。

{
"version": "1.0.0",
"name": "asp.net",
"private": true,
"devDependencies": {
"bootstrap": "4.1.3",
"jquery": "3.3.1",
"jquery-validation": "1.17.0",
"jquery-validation-unobtrusive": "3.2.10",
"jquery-ajax-unobtrusive": "3.2.4"
}
}

bundleconfig.json文件用来打包js文件和css文件。问了使用这个打包功能,先安装BuildBundlerMinifer包。

js类库被打包成了两个不同的文件, vendor-min.jsvendor-validation-min.js

// Vendor JS
{
"outputFileName": "wwwroot/js/vendor.min.js",
"inputFiles": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
],
"minify": {
"enabled": true,
"renameLocals": true
},
"sourceMap": false
},
// Vendor Validation JS
{
"outputFileName": "wwwroot/js/vendor-validation.min.js",
"inputFiles": [
"node_modules/jquery-validation/dist/jquery.validate.min.js",
"node_modules/jquery-validation/dist/additional-methods.js",
"node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js",
"node_modules//jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.min.js"
],
"minify": {
"enabled": true,
"renameLocals": true
},
"sourceMap": false
}

全局打包文件可以添加到_Layout.cshtml文件中。

<script src="~/js/vendor.min.js" asp-append-version="true"></script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
@RenderSection("scripts", required: false)
</body>

将validation打包文件添加到_ValidationScriptsPartial.cshtml中。

<script src="~/js/vendor-validation.min.js" asp-append-version="true"></script>

然后就可以将其添加到需要的视图中去。

@section Scripts  {
@await Html.PartialAsync("_ValidationScriptsPartial")
}

简单的AJAX的表单请求

通过添加一些html attribute到表单元素上可以将一个表单请求作为一个ajax请求发送。当请求结束,id为data-ajax-update指定的div将被替换为相应结果。Html.PartialAsync调用初始的视图。

@{
ViewData["Title"] = "Ajax Test Page";
} <h4>Ajax Test</h4> <form asp-action="Index" asp-controller="AjaxTest"
data-ajax="true"
data-ajax-method="POST"
data-ajax-mode="replace"
data-ajax-update="#ajaxresult" > <div id="ajaxresult">
@await Html.PartialAsync("_partialAjaxForm")
</div>
</form> @section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}

_partialAjaxForm.cshtml视图实现了表单的一些内容。

@model AspNetCoreBootstrap4Validation.ViewModels.AjaxValidationModel 

<div asp-validation-summary="All" class="text-danger"></div>

<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" asp-for="Name"
id="AjaxValidationModelName" aria-describedby="nameHelp"
placeholder="Enter name">
<small id="nameHelp" class="form-text text-muted">
We'll never share your name ...
</small>
<span asp-validation-for="Name" class="text-danger"></span>
</div> <div class="form-group">
<label for="age">Age</label>
<input type="number" class="form-control"
id="AjaxValidationModelAge" asp-for="Age" placeholder="0">
<span asp-validation-for="Age" class="text-danger"></span>
</div> <div class="form-check ten_px_bottom">
<input type="checkbox" class="form-check-input big_checkbox"
asp-for="IsCool" id="AjaxValidationModelIsCool">
<label class="form-check-label ten_px_left" for="IsCool">IsCool</label>
<span asp-validation-for="IsCool" class="text-danger"></span>
</div> <button type="submit" class="btn btn-primary">Submit</button>

下面例子中的第一个Index方法,仅用来相应HTTP GET请求。

第二个Index方法接收一个POST请求,其中包括了每次都会发送的Anti-Forgery token。成功后,返回一个部分视图,并清空model state,否则validation messages不会被重置。

public class AjaxTestController : Controller
{
public IActionResult Index()
{
return View(new AjaxValidationModel());
} [HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(AjaxValidationModel model)
{
if (!ModelState.IsValid)
{
return PartialView("_partialAjaxForm", model);
} // the client could validate this, but allowed for testing server errors
if(model.Name.Length < 3)
{
ModelState.AddModelError("name", "Name should be longer than 2 chars");
return PartialView("_partialAjaxForm", model);
} ModelState.Clear();
return PartialView("_partialAjaxForm");
}
}

复杂的ajax表单请求

这个例子中会返回一个数据集合到视图,每个数据子项都有一个表单用来更新这个子项的数据,通过checkbox的onchange事件,文本框的oninput事件来触发请求。

因为是一个数据集合,因此每个子项所用的div元素都必须有一个唯一的id。可以通过为每一个子项生成一个GUID来实现,用它作为data-ajax-update的一部分。

@using AspNetCoreBootstrap4Validation.ViewModels
@model AjaxValidationListModel
@{
ViewData["Title"] = "Ajax Test Page";
} <h4>Ajax Test</h4> @foreach (var item in Model.Items)
{
string guid = Guid.NewGuid().ToString(); <form asp-action="Index" asp-controller="AjaxComplexList"
data-ajax="true"
data-ajax-method="POST"
data-ajax-mode="replace"
data-ajax-update="#complex-ajax-@guid"> <div id="complex-ajax-@guid">
@await Html.PartialAsync("_partialComplexAjaxForm", item)
</div>
</form>
} @section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
@model AspNetCoreBootstrap4Validation.ViewModels.AjaxValidationModel
@{
string guid = Guid.NewGuid().ToString();
} <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group">
<label for="name">Name</label> <input type="text" class="form-control" asp-for="Name"
id="AjaxValidationModelName" aria-describedby="nameHelp" placeholder="Enter name"
oninput="$('#submit-@guid').trigger('submit');"> <small id="nameHelp" class="form-text text-muted">We'll never share your name ...</small>
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label for="age">Age</label> <input type="number" asp-for="Age"
class="form-control" id="AjaxValidationModelAge" placeholder="0"
oninput="$('#submit-@guid').trigger('submit');"> <span asp-validation-for="Age" class="text-danger"></span>
</div>
<div class="form-check ten_px_bottom"> @Html.CheckBox("IsCool", Model.IsCool,
new { onchange = "$('#submit-" + @guid + "').trigger('submit');", @class = "big_checkbox" }) <label class="form-check-label ten_px_left" >Check the checkbox to send a request</label>
</div> <button style="display: none" id="submit-@guid" type="submit">Submit</button>

控制器的代码和之前的一样。

using AspNetCoreBootstrap4Validation.ViewModels;

namespace AspNetCoreBootstrap4Validation.Controllers
{
public class AjaxComplexListController : Controller
{
public IActionResult Index()
{
return View(new AjaxValidationListModel {
Items = new List<AjaxValidationModel> {
new AjaxValidationModel(),
new AjaxValidationModel()
}
});
} [HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(AjaxValidationModel model)
{
if (!ModelState.IsValid)
{
return PartialView("_partialComplexAjaxForm", model);
} // the client could validate this, but allowed for testing server errors
if(model.Name.Length < 3)
{
ModelState.AddModelError("name", "Name should be longer than 2 chars");
return PartialView("_partialComplexAjaxForm", model);
} ModelState.Clear();
return PartialView("_partialComplexAjaxForm", model);
}
}
}

[译]asp-net-core-mvc-ajax-form-requests-using-jquery-unobtrusive的更多相关文章

  1. Upload Files In ASP.NET Core 1.0 (Form POST And JQuery Ajax)

    Uploading files is a common requirement in web applications. In ASP.NET Core 1.0 uploading files and ...

  2. ASP.Net Core MVC+Ajax 跨域

    要求 C端:用户端(http://www.b.com) A端:管理端(http://admin.b.com) 问题:A端上传图片到C端指定文件夹内保存,供C端使用. 方案 ① C端从nuget引入Mi ...

  3. asp.net Core MVC + form validation + ajax form 笔记

    asp.net Core MVC 有特别处理form,controller可以自己处理model的验证,最大的优势是写form时可以少写代码 先了解tag helper ,这东西就是element上的 ...

  4. ASP.NET Core MVC – Form Tag Helpers

    ASP.NET Core Tag Helpers系列目录 ASP.NET Core MVC Tag Helpers 介绍 ASP.NET Core MVC – Caching Tag Helpers ...

  5. 剖析ASP.NET Core MVC(Part 1)- AddMvcCore(译)

    原文:https://www.stevejgordon.co.uk/asp-net-core-mvc-anatomy-addmvccore发布于:2017年3月环境:ASP.NET Core 1.1 ...

  6. ASP.NET Core MVC/WebAPi 模型绑定探索

    前言 相信一直关注我的园友都知道,我写的博文都没有特别枯燥理论性的东西,主要是当每开启一门新的技术之旅时,刚开始就直接去看底层实现原理,第一会感觉索然无味,第二也不明白到底为何要这样做,所以只有当你用 ...

  7. ASP.NET Core 中文文档 第四章 MVC(01)ASP.NET Core MVC 概览

    原文:Overview of ASP.NET Core MVC 作者:Steve Smith 翻译:张海龙(jiechen) 校对:高嵩 ASP.NET Core MVC 是使用模型-视图-控制器(M ...

  8. Working with Data » 使用Visual Studio开发ASP.NET Core MVC and Entity Framework Core初学者教程

    原文地址:https://docs.asp.net/en/latest/data/ef-mvc/intro.html The Contoso University sample web applica ...

  9. ASP.NET Core MVC上传、导入、导出知多少

    前言 本君已成夜猫子,本节我们来讲讲ASP.NET Core MVC中的上传,这两天才研究批量导入功能,本节顺便简单搞搞导入.导出,等博主弄妥当了再来和大家一并分享. .NET Core MVC上传 ...

  10. 007.Adding a view to an ASP.NET Core MVC app -- 【在asp.net core mvc中添加视图】

    Adding a view to an ASP.NET Core MVC app 在asp.net core mvc中添加视图 2017-3-4 7 分钟阅读时长 本文内容 1.Changing vi ...

随机推荐

  1. vue watch监听验证码时,axios延迟发送post请求。

    标题写的全面一些,方便其他人检索,我就是找了半天找不到资料,最后自己搞定了. 原理: 每次监听到输入值变化,就打一个时间戳,然后暂停2秒再去提交post验证. 但是每次提交前,判断一下之前打的时间戳和 ...

  2. Linux- 常用命令, Vim编辑器操作

    1.Linux命令: ls >查看列表(蓝色为文件夹,白色为文件) ls -a >显示包括隐藏文件的所有文件 ls -l >以列表的形式显示 ls -lh >类似于ls -l ...

  3. 简单介绍python的双向队列

    介绍 大家都知道利用 .append 和 .pop 方法,我们可以把列表当作栈或者队列来用(比如,把 append 和 pop(0) 合起来用,就能模拟栈的“先进先出”的特点).但是删除列表的第一个元 ...

  4. eclipse java formater 配置详解

    comment.insert_new_line_before_root_tags(insert/do_not_insert):在Javadoc根标记块前插入空行,默认为insert: insert_s ...

  5. IdentityServer4客户端如何获取自定义声明,了解一下?

    前言 久违了各位,之前录制过IdentityServer4的基础视频(https://space.bilibili.com/319652230/#/),有兴趣了解的童鞋可以看一下,只不过未发表成博客. ...

  6. form单选框

    form中的单选框: var resultStartRadio = new Ext.form.RadioGroup({ id : 'resultStartRadio', name :"for ...

  7. python_while

    while 格式 while 条件 : pass 使用 while True : print("精忠报国") print("粉红的回忆") print(&quo ...

  8. css 3 新特性

    CSS3的新特性大致分为以下六类 1.CSS3选择器 2.CSS3边框与圆角 3.CSS3背景与渐变 4.CSS3过渡 5.CSS3变换 6.CSS3动画 下面分别说一说以上六类都有哪些内容 CSS3 ...

  9. 设置tomcat开机自启和后台运行

    前言:程序登录遇到了问题,重启服务器上的tomcat后程序可以正常的使用,是通过进入bin目录,双击startup.bat运行启动的程序,此时会弹出启动窗口,而且该窗口不能关闭,这个窗口是tomcat ...

  10. 利用控制台承载SignalR作为服务端、及第三方推送信息

    一 首先建立一个控制台需要引用一些组件 特别要注意引用Microsoft.Owin.Host.HttpListener别忘了这个组件,不引用他可能程序正常运行不会报错,但服务器一直开启失败(我之前就是 ...