博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC中Unobtrusive Ajax的妙用
阅读量:6880 次
发布时间:2019-06-27

本文共 2654 字,大约阅读时间需要 8 分钟。

Unobtrusive Javascript有三层含义:一是在HTML代码中不会随意的插入Javsscript代码,只在标签中加一些额外的属性值,然后被引用的脚本文件识别和处理;二是通过脚本文件所增加的功能是一种渐进式的增强,当客户端不支持或禁用了Javsscript时网页所提供的功能仍然能够实现,只是用户体验会降低;三是能够兼容不同的浏览器。

启用Unobtrusive Javascript的步骤:

1.在web.config文件中加入

2.在网页中加入

   

使用Unobtrusive Ajax主要有两个用途:做客户端的输入验证和异步的表单提交。客户端验证基本上是自动的,不用做特别的处理。下面用一个例子重点说一下提交表单。

数据模型是这样的:每个类别有很多属性,属性可以分组,属性组可以嵌套。然后在网页创建和编辑属性组,示意图如下:

这是我半年前写的代码:

$(this).find(".CreatePropertyGroup").click(function () {
$(".InputGroupName").hide(); var id = $(this).next().val(); var td = $(this).parent().parent(); $.post("/Category/CreatePropertyGroup", { parentId: id, name: $(this).prev().val() }, function () {
td.load("/Category/PropertyGroup", { "id": id, "resultType": "html" }, loadGroupReady); }); });
$(this).find(".CreateProperty").click(function () {
$(".InputPropertyName").hide(); var id = $(this).next().val(); var name = $(this).parent().find(".PropertyName").val(); var type = $(this).parent().find("#PropertyDataType").val(); var unit = $(this).parent().find(".PropertyUnit").val(); var range = $(this).parent().find(".ValueRange").val(); var td = $(this).parent().parent(); $.post("/Category/CreateProperty", { groupId: id, name: name, type: type, unit: unit, range: range }, function () {
td.load("/Category/PropertyGroup", { "id": id, "resultType": "html" }, loadGroupReady); }); });

完全使用jQuery获取控件值和提交,可读性和可维护性不是很好。现在改用Ajax.BeginForm之后,很大地简化了编程:

对于不使用的表单的,直接点链接的可以用Ajax.ActionLink:

        @Ajax.ActionLink("删除", "DeletePropertyGroup", new { categoryId = categoryId, path = path, name = property.Name },        new AjaxOptions        {
HttpMethod = "Post", Url = Url.Action("DeletePropertyGroup", new { categoryId = categoryId, path = path, name = property.Name }), Confirm = "确认要删除 '" + property.Name + "' 及其所有属性吗?", UpdateTargetId = "PropertyGroup" })

最终运行后生成的代码如下:

属性组名称:

可以看到魔力就在于以data-ajax开头的一些属性中,当Javascript被禁用后,表单仍能提交,链接也能点开,只不过不再是异步的了。

转载于:https://www.cnblogs.com/webenh/p/6165325.html

你可能感兴趣的文章
关于passive event listener的一次踩坑
查看>>
BlockingQueue与Condition原理解析
查看>>
webpack 3 零基础入门教程 #1 - 介绍
查看>>
Spark资源调度参数调优深入剖析-Spark商业调优实战
查看>>
node 实现简单的数据交互入门
查看>>
开发多页面的Vue应用遇到的问题
查看>>
消息未读之点不完的小红点(Node+Websocket)
查看>>
ajax的理解
查看>>
iOS开发 @rpath,@loader_path,@executable_path的使用
查看>>
浅谈node的模块机制的实现
查看>>
模拟app页面出现消失动画效果
查看>>
基于 HTML5 WebGL 的低碳工业园区监控系统
查看>>
『中级篇』CI/CD持续集成/持续部署(69)
查看>>
JS垃圾回收机制笔记
查看>>
Reactor Model
查看>>
mmall_v2.0 Redis + Cookie 实现单点登录
查看>>
Docker - 02 创建镜像 Dockerfile 指令速查表
查看>>
学习 JavaScript (三)核心概念:语法、变量、数据类型
查看>>
源码分析 — ARouter
查看>>
华山论剑之iOS&tableView的双剑合璧
查看>>