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($"成功!");
}

相关推荐

  1. 04_前后交互技术Ajax异步请求

    2024-07-19 08:18:04       42 阅读
  2. 05_前后交互技术Ajax案例讲解

    2024-07-19 08:18:04       47 阅读
  3. Web前后交互

    2024-07-19 08:18:04       24 阅读
  4. web3以太坊开发前后交互中涉及到的合约

    2024-07-19 08:18:04       145 阅读
  5. Vue2 基础前后交互

    2024-07-19 08:18:04       25 阅读
  6. “探索AJAX前端与后数据交互的利器“

    2024-07-19 08:18:04       44 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-19 08:18:04       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-19 08:18:04       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-19 08:18:04       58 阅读
  4. Python语言-面向对象

    2024-07-19 08:18:04       69 阅读

热门阅读

  1. 探索.NET内存之海:垃圾回收的艺术与实践

    2024-07-19 08:18:04       22 阅读
  2. 【.NET全栈】ASP.NET开发Web应用——Web部件技术

    2024-07-19 08:18:04       18 阅读
  3. 基于Gunicorn、Flask和Docker的高并发部署

    2024-07-19 08:18:04       20 阅读
  4. ArcGIS Pro SDK (九)几何 5 多边形

    2024-07-19 08:18:04       21 阅读
  5. SpringBoot集成EasyExcel实现模板写入多个sheet导出

    2024-07-19 08:18:04       21 阅读
  6. python中excel的读取和写入

    2024-07-19 08:18:04       20 阅读
  7. Python 3 CGI编程

    2024-07-19 08:18:04       19 阅读
  8. 为什么 HashMap 的容量是 2 的整次幂?

    2024-07-19 08:18:04       16 阅读
  9. C++编程逻辑讲解step by step:利用文档类处理数据

    2024-07-19 08:18:04       20 阅读
  10. 【Oracle】Oracle中的LISTAGG函数

    2024-07-19 08:18:04       19 阅读
  11. new和malloc

    2024-07-19 08:18:04       22 阅读
  12. Redis 地理位置 GEO 模块

    2024-07-19 08:18:04       21 阅读