瑞安做网站的公司,微信小程序怎么制作自己的程序,杭州vi设计策划,网帆网站建设目录
一、后端
二、前端
三、代码位置
四、实现效果
五、关键的点
1.后端传输给前端#xff1a;
2.前端传输给后端
一、后端
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using WebAppl…目录
一、后端
二、前端
三、代码位置
四、实现效果
五、关键的点
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(){// 构造学生列表数据ListStudent students new ListStudent{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] ListStudent result)//用[FromBody]来接收{// 返回示例假设直接返回成功信息return Content($成功);}}
}二、前端
using static WebApplication1.Controllers.MainController
{var stulist ViewData[Students] as ListStudent;//声明后端的ViewData注意需要as关键字转化为实体
}h2学生列表/h2foreach (var student in stulist)//声明过后可以直接遍历
{diva classstudent-link href# data-student-idstudent.Id data-student-namestudent.Namestudent.Name/a/div
}button idsubmitButton我是一个按钮/button
script srchttps://code.jquery.com/jquery-3.6.0.min.js/scriptscriptvar selectedStudentId null;var selectedStudentName null;$(document).ready(function () {//classstudent-link订阅点击事件$(.student-link).click(function () {// 获取被点击链接的数据selectedStudentId $(this).data(student-id);selectedStudentName $(this).data(student-name);console.log(Selected student: id${selectedStudentId}, name${selectedStudentName});//打印到控制台});//idsubmitButton订阅点击事件$(#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 ListStudent;//声明后端的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] ListStudent result)//用[FromBody]来接收 { // 返回示例假设直接返回成功信息 return Content($成功); }