如何在C# ASP.Net MVC中利用复选框选中值筛选归档客户
实现步骤
一、修正前端AngularJS代码
1. 修复includeFlagsChanged函数
当前函数逻辑错误,复选框状态改变时需重新加载数据以刷新客户列表:
$scope.includeFlagsChanged = function () { initialise(); };
2. 修改initialise方法,传递复选框参数给后端
将includeArchived作为请求体参数发送到后端,修正请求逻辑:
var initialise = function () { $http.post("/DataLink/GetCustomerLinks", { includeArchived: $scope.includeArchived }) .then(function (response) { $scope.error = null; $scope.response = response; if (response.data.Success) { $scope.customers = response.data.customers; $scope.wcCustomers = response.data.wcCustomers; } else { $scope.error = response.data.Exception; } }, function (response) { $scope.error = response }); }
注:原代码中
includeArchived: $scope.includeArchived写在then回调内无效,需放在post的第二个参数位置作为请求数据。
二、修改后端C#代码
1. 让GetCustomerLinks方法接收前端参数
添加[FromBody]标记接收请求体中的布尔值:
public async Task<JsonResult> GetCustomerLinks([FromBody] bool includeArchived) { try { var xeroSession = new XeroSessionManager(); var xeroData = new XeroData(xeroSession); var xeroCustomers = await xeroData.GetAllCustomers(); using (var cx = new BillingAssistantContext()) { var wcCustomers = cx.Companies.Select(c => new { wcId = c.ID, wcName = c.Name }).OrderBy(c => c.wcName).ToArray(); // 构建客户查询 var customersQuery = xeroCustomers.Select(xc => { var cl = cx.CustomerLinks.SingleOrDefault(l => l.XeroContactID == xc.ContactID); return new { xeroId = xc.ContactID, xeroName = xc.Name, wcCustomerId = cl?.WCompanyID, archived = cl?.Archived }; }); // 根据参数筛选客户:未勾选则只显示非归档,勾选则显示全部 if (!includeArchived) { customersQuery = customersQuery.Where(xc => xc.archived == false); } var customers = customersQuery.OrderBy(xc => xc.xeroName).ToArray(); return new JsonResult { Data = new { Success = true, customers = customers, wcCustomers = wcCustomers, } }; } } catch (Exception ex) { return new JsonResult { Data = new { Success = false, Exception = ex.Message } }; } }
三、验证流程
- 页面初始化时,
includeArchived默认值为false,后端返回非归档客户 - 勾选复选框时,触发
includeFlagsChanged调用initialise,传递true给后端,返回所有客户 - 取消勾选时,传递
false,后端重新返回非归档客户
内容的提问来源于stack exchange,提问作者JulyAnn Jackson
相关产品推荐
相关产品推荐

