博客
关于我
强烈建议你试试无所不能的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

你可能感兴趣的文章
创业板跌跌不休
查看>>
类,对象,方法,变量
查看>>
导航和渲染首页文章列表
查看>>
Unity脚本用VS打开出现 "以下文件中的行尾不一致,要将行尾标准化吗?"
查看>>
开始Flask项目
查看>>
linux命令---常用组合
查看>>
深入理解OOP(第一天):多态和继承(初期绑定和编译时多态)
查看>>
JS获取select 当前选种值
查看>>
requestAnimFrame 动画的使用方法
查看>>
php-面向对象
查看>>
关于坑爹的编解码问题
查看>>
服务器渲染和客户端渲染学习笔记
查看>>
orcale 匿名代码块
查看>>
设计模式-代理
查看>>
Java HotSpot VM Options 参数设置
查看>>
java 生成注释文档
查看>>
Linux内存管理--基本概念【转】
查看>>
深入理解CMA【转】
查看>>
kmalloc vmalloc kzalloc malloc 和 get_free_page()【转】
查看>>
Spring @Value注解使用${}进行注入(转)
查看>>