当前位置: 首页 > news >正文

Web开发:ASP.NET CORE前后端交互之AJAX(含基础Demo)

目录

一、后端

二、前端

三、代码位置

四、实现效果

五、关键的点

1.后端传输给前端:

2.前端传输给后端

一、后端

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebApplication1.Models;namespace WebApplication1.Controllers
{public class MainController : Controller{public class Student{public int Id { get; set; }public string Name { get; set; }}public IActionResult Index(){// 构造学生列表数据List<Student> students = new List<Student>{new Student { Id = 1, Name = "Alice" },new Student { Id = 2, Name = "Bob" },new Student { Id = 3, Name = "Charlie" }};ViewData["Students"]= students; return View(); // 将学生列表传递给视图}[HttpPost]public ActionResult ProcessStudent([FromBody] List<Student> result)//用[FromBody]来接收{// 返回示例:假设直接返回成功信息return Content($"成功!");}}
}

二、前端

@using static WebApplication1.Controllers.MainController
@{var stulist = ViewData["Students"] as List<Student>;//声明后端的ViewData,注意需要as关键字转化为实体
}<h2>学生列表</h2>@foreach (var student in stulist)//声明过后可以直接遍历
{<div><a class="student-link" href="#" data-student-id="@student.Id" data-student-name="@student.Name">@student.Name</a></div>
}<button id="submitButton">我是一个按钮</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script><script>var selectedStudentId = null;var selectedStudentName = null;$(document).ready(function () {//class=student-link订阅点击事件$('.student-link').click(function () {// 获取被点击链接的数据selectedStudentId = $(this).data('student-id');selectedStudentName = $(this).data('student-name');console.log(`Selected student: id=${selectedStudentId}, name=${selectedStudentName}`);//打印到控制台});//id=submitButton订阅点击事件$('#submitButton').click(function () {var allStudents = []; // 存放所有学生信息// 遍历所有学生,收集学生信息$('.student-link').each(function () {var studentId = $(this).data('student-id');//自定义属性不可以用Val()var studentName = $(this).data('student-name');allStudents.push({ id: studentId, name: studentName });//存入列表中});// 在这里提交所有学生信息$.ajax({url: '@Url.Action("ProcessStudent", "Main")',//将发送一个POST请求到MainController的ProcessStudent方法中type: 'POST',contentType: 'application/json',data: JSON.stringify(allStudents),//JSON格式发送success: function (response) {alert('后端成功响应: ' + response);},error: function () {alert('后端未成功相应');}});});});
</script>

三、代码位置

四、实现效果

五、关键的点

1.后端传输给前端:

①需要声明和强制转换

@{var stulist = ViewData["Students"] as List<Student>;//声明后端的ViewData,注意需要as关键字转化为实体
}

②只能在同一个控制器+方法名传输,例如Controller/MainController的Index方法的ViewData(或者ViewBag)只可以传输给Views/Main/Index.cshtml,不能够传递给其余前端界面。

2.前端传输给后端

①需要写清楚url和type(传输类型),以下url表示发送一个POST请求到MainController的ProcessStudent方法中

url: '@Url.Action("ProcessStudent", "Main")'
type: 'POST',

②后端接收也需要注明类型方法名(要和前端一一对应好),用JSON传递还需要加上[FromBody]强制转化为实体

[HttpPost]
public ActionResult ProcessStudent([FromBody] List<Student> result)//用[FromBody]来接收
{
    // 返回示例:假设直接返回成功信息
    return Content($"成功!");
}

http://www.lryc.cn/news/402421.html

相关文章:

  • 经典神经网络(14)T5模型原理详解及其微调(文本摘要)
  • C语言结构体字节对齐技术详解
  • Linux编辑器——vim的使用
  • Java案例斗地主游戏
  • sqlite|轻量数据库|pgadmin4的sqlite数据库操作--重置密码和账号解锁
  • 【ARMv8/v9 异常模型入门及渐进 9.1 - FIQ 和 IRQ 打开和关闭】
  • 深入探索Flutter中的状态管理:使用Provider库
  • 算法工程师第十四天(找树左下角的值 路径总和 从中序与后序遍历序列构造二叉树 )
  • memcached 高性能内存对象缓存
  • C语言 分割链表
  • spring ioc的原理
  • npm安装依赖包报错,npm ERR! code ENOTFOUND
  • 【iOS】——内存对齐
  • 网络安全-网络安全及其防护措施10
  • Pytorch基础应用
  • Axure 教程 | 设置文本框背景透明
  • 【BUG】已解决:NOAUTH Authentication required
  • 全国产服务器主板:搭载飞腾FT2000+/64处理器的高性能加固服务器
  • OPC UA边缘计算耦合器BL205工业通信的最佳解决方案
  • 【已解决】Django连接MySQL启动报错Did you install mysqlclient?
  • ubuntu gcc g++版本切换
  • 如何发一篇顶会论文? 涉及3D高斯,slam,自动驾驶,三维点云等等
  • Java面试八股之什么是Redis的缓存更新
  • 新华三H3CNE网络工程师认证—VLAN使用场景与原理
  • Linux-开机自动挂载(文件系统、交换空间)
  • [003-02-10].第10节:Docker环境下搭建Redis主从复制架构
  • uni-app学习HBuilderX学习-微信开发者工具配置
  • 持续集成08--Jenkins邮箱发送构建信息及测试报告
  • 专题四:设计模式总览
  • 基于X86+FPGA+AI数字化医疗设备:全自动尿沉渣检测仪