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

【日志输出控制台和获取连接字符串】

  public class HomeController : Controller
  {
      private readonly ILogger<HomeController> _logger;
      public static bool Loginflag = false;
      private readonly IConfiguration _configuration;

      public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
      {
          _logger = logger;
          _configuration = configuration;
      }

      public IActionResult Index()
      {
          string connectionString = _configuration.GetConnectionString("DefaultConnection");
          _logger.LogInformation("访问了 Index 页面");
      }

}

appsetting.json 

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

【效果】

【说明】 appsettings.json和launchsettings.json区别:

功能不同: 

  • appsettings.json 用于应用程序配置(例如连接字符串)。
  • launchsettings.json 用于开发工具的调试和运行配置(例如IIS配置,启动url配置)。

位置不同: 

  • appsettings.json 项目的根目录
  • launchsettings.json 开发工具的配置目录中(根目录/Properties)

二、前端

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值