jQuery 将 Ajax 调用中的数据传递给 MVC 操作方法
Posted
技术标签:
【中文标题】jQuery 将 Ajax 调用中的数据传递给 MVC 操作方法【英文标题】:jQuery to pass data in Ajax call to MVC action method 【发布时间】:2020-11-22 15:37:14 【问题描述】:我准备并填充了两个列表(左列表和右列表)。 然后我有这个 JS 代码将元素从一个列表移动到另一个列表。 而且效果很好。
$(function ()
$('body').on('click', '.list-group .list-group-item', function ()
$(this).toggleClass('active');
);
$('.list-arrows button').click(function ()
var $button = $(this), actives = '';
if ($button.hasClass('move-left'))
actives = $('.list-right ul li.active');
actives.clone().appendTo('.list-left ul');
actives.remove();
else if ($button.hasClass('move-right'))
actives = $('.list-left ul li.active');
actives.clone().appendTo('.list-right ul');
actives.remove();
);
);
但老实说,当用户单击表单上的提交按钮时,我不知道如何将结果传递回代码隐藏?
这是我的cshtml代码:
@using AuthDatabase.Entities
@using Identity.Models
@model RoleEdit
@
ViewData["Title"] = "Edit role";
Layout = "~/Views/Shared/_Layout.cshtml";
<h1>@ViewData["Title"]</h1>
<br />
<h4>Roles</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
<form method="post">
<input type="hidden" name="roleName" value="@Model.Role.Name" />
<input type="hidden" name="roleId" value="@Model.Role.Id" />
<div class="row">
<div class="dual-list list-left col-md-5">
<h5>No roles</h5>
<div class="well text-right">
<div class="row">
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"></span>
<input type="text" name="SearchDualList" class="form-control" placeholder="search" />
</div>
</div>
</div>
<ul class="list-group">
@foreach (AppUser user in Model.NonMembers)
<li class="list-group-item">@user.UserName</li>
</ul>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button class="btn btn-default btn-sm move-left" type="button">
<span class="btn btn-primary"><</span>
</button>
<button class="btn btn-default btn-sm move-right" type="button">
<span class="btn btn-primary">></span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<h5>With roles</h5>
<div class="well">
<div class="row">
<div class="col-md-10">
<div class="input-group">
<input type="text" name="SearchDualList" class="form-control" placeholder="search" />
<span class="input-group-addon glyphicon glyphicon-search"></span>
</div>
</div>
</div>
<ul class="list-group">
@foreach (AppUser user in Model.Members)
<li class="list-group-item">@user.UserName</li>
</ul>
</div>
</div>
</div>
<br />
<a asp-action="Index" class="btn btn-secondary">Back to List</a>
<button type="submit" class="btn btn-primary">Save</button>
</form>
@section Scripts
<script src="~/js/lists.js" asp-append-version="true"></script>
还有我的控制器:
public async Task<IActionResult> Edit(string id)
IdentityRole role = await _roleManager.FindByIdAsync(id);
List<AppUser> members = new List<AppUser>();
List<AppUser> nonMembers = new List<AppUser>();
foreach (AppUser user in _userManager.Users)
var list = await _userManager.IsInRoleAsync(user, role.Name) ? members : nonMembers;
list.Add(user);
return View(new RoleEdit
Role = role,
Members = members,
NonMembers = nonMembers
);
[HttpPost]
public async Task<IActionResult> Edit(RoleModification model)
IdentityResult result;
if (ModelState.IsValid)
foreach (string userId in model.AddIds ?? new string[] )
AppUser user = await _userManager.FindByIdAsync(userId);
if (user != null)
result = await _userManager.AddToRoleAsync(user, model.RoleName);
if (!result.Succeeded)
Errors(result);
foreach (string userId in model.DeleteIds ?? new string[] )
AppUser user = await _userManager.FindByIdAsync(userId);
if (user != null)
result = await _userManager.RemoveFromRoleAsync(user, model.RoleName);
if (!result.Succeeded)
Errors(result);
if (ModelState.IsValid)
return RedirectToAction(nameof(Index));
else
return await Edit(model.RoleId);
[HttpPost] 编辑操作需要具有两个字符串数组的 RoleModification 对象(列表上的更改 -> 它现在基于之前没有 jquery 的解决方案)。也适合只通过一个列表权限。
public class RoleModification
[Required]
public string RoleName get; set;
public string RoleId get; set;
public string[] AddIds get; set;
public string[] DeleteIds get; set;
【问题讨论】:
【参考方案1】: $('#submitBtn').on('click', function ()
let addIds = [];
$('.list-right ul li').each(function (index)
addIds.push($(this).text());
);
ajaxSubmit(addIds);
);
);
function ajaxSubmit(input)
$.ajax(
url:'/controller/action',
method:'POST',
data:input --- or input
success:function()
console.log('success');,
error:function(x,y,z)
console.log(x,y,z);
);
你的控制器必须是这样的
public ActionResult Edit(List<string> input)
【讨论】:
全长你可以阅读这个***.com/questions/39129555/…@Krzysztof Patra 感谢您的帮助。我正在寻找更简单的东西(不使用 Ajax)。认为可以将修改后的数据发送回 MVC 中的绑定模型。不过,使用 Ajax 的解决方案效果很好。【参考方案2】: 将其更改为@using(Html.BeginForm("Action","Controller"))your html here
你也可以这样做
$.ajax(
url:'/controller/action',
data:form,
success:function()alert('submitted');,
error:function(x,y,z)console.log(x,y,z);
);
基本上 mvc 解析器搜索名称标签与模型 btw 相同的元素
public string[] AddIds get; set;
public string[] DeleteIds get; set;
这两个字段很棘手
var addIds = ['a','b'];
同样适用于 DeleteIds 然后创建一个包含后端所需的所有字段的父对象 值得一提的是,你可以在带有@的js中使用剃须刀,在带有@的剃须刀中使用js: 所以你可以做这样的事情
@foreach(var id in AddIds)
@:addIds.add(@id);
最后但并非最不重要的一点是,您可以挂钩一个事件并监听它并触发提交
$('window').ready(function()
$('#yourSubmitButtonId').on('click',function()
$('form').submit();
);
);
【讨论】:
如果您认为自己有答案,请标记为答案,否则我很乐意添加信息 仍然卡住。我设法做到了这样的事情:$('window').ready(function () $('#submitBtn').on('click', function () let addIds = []; $('.list-right ul li').each(function (index) addIds.push($(this).text()); ); $('form').submit(); ); );
当用户保存表单并准备一个名为 addIds 的数组和正确的 Id 列表时,它会被触发。但是 addIds 仍然没有与 httpPost 操作所需的模型绑定。
基本上,当您创建具有相同名称的多实例时,mvc 解析器将其作为一个很棒的数组,因此 foreach 循环例如 addIds 并在每个元素中创建具有确切名称 addIds 的隐藏元素,mvc 解析器将其转换为string[] addIds【参考方案3】:
cshtml
@model HelloWorldMvcApp.SampleViewModel
@
Layout = null;
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Bootstrap 101 Template</title>
</head>
<body>
@using(Html.BeginForm("GetAnswer","Home"))
<ul>
@foreach(var item in Model.questions)
<input type="hidden" value="@item" name="questions"/>
<li>@item</li>
@foreach(var item2 in Model.questions2)
<input type="hidden" value="@item2" name="questions"/>
<li>@item2</li>
</ul>
@Model.text
<input type="hidden" value="asd3" name="text"/>
<input type="submit" value="submit"/>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
</body>
</html>
视图模型
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace HelloWorldMvcApp
public class SampleViewModel
public SampleViewModel()
this.questions = new string[2];
this.questions2 = new string[2];
public string[] questions get; set;
public string[] questions2 get; set;
public string text get;set;
控制器
using System;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace HelloWorldMvcApp
public class HomeController : Controller
[HttpGet]
public ActionResult Index()
SampleViewModel model = new SampleViewModel();
model.questions.SetValue("Test Data",0);
model.questions.SetValue("Test Data2",1);
model.questions2.SetValue("Test Data",0);
model.questions2.SetValue("Test Data2",1);
return View(model);
[HttpPost]
public ActionResult GetAnswer(SampleViewModel model)
return View(model);
如您所见,它将字符串数组和字符串作为对象传递给 mvc 控制器
【讨论】:
以上是关于jQuery 将 Ajax 调用中的数据传递给 MVC 操作方法的主要内容,如果未能解决你的问题,请参考以下文章