c# - 使用用户修改 DropdownList MVC?
问题描述
事实证明,我有一个来自级联下拉列表的 Jquery,它包含来自地区和服务的数据,我希望当用户登录时,只显示用户来自的地区的数据,用户有一个分配的地区.
这是我在控制器上的代码:
public JsonResult GetServices(int districtId)
{
db.Configuration.ProxyCreationEnabled = false;
var services = db.Services.Where(s => s.DistrictId == districtId).OrderBy(s => s.Name);
return Json(services);
}
这是我的 Jquery 脚本:
<script type="text/javascript">
$(document).ready(function () {
$("#DistrictId").change(function () {
$("#ServiceId").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetServices")',
dataType: 'json',
data: { districtId: $("#DistrictId").val() },
success: function (districts) {
$.each(districts, function (i, service) {
$("#ServiceId").append('<option value="'
+ service.ServiceId + '">'
+ service.Name + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve services.' + ex);
}
});
return false;
})
});
</script>
我的观点:
<div class="form-group">
@Html.LabelFor(model => model.DistrictId, "District", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DistrictId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.DistrictId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ServiceId, "Service", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ServiceId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ServiceId, "", new { @class = "text-danger" })
</div>
</div>
解决方案
假设登录的用户正在使用控制器方法。您可以获取用户并通过他的地区 id 进行过滤,而无需将其作为参数发送。如果您在同一个视图中有两个下拉菜单,那么您所做的似乎没问题。如果问题是它永远不会进入方法,请确保在这种情况下使用相应的 Http Verb POST。
[HttpPost]
public JsonResult GetUserServices()
{
var user = userManager.FindByNameAsync(User.Identity.Name);
db.Configuration.ProxyCreationEnabled = false;
var services = db.Services
.Where(s => s.DistrictId == user.DistrictId)
.OrderBy(s => s.Name);
return Json(services);
}
推荐阅读
- amazon-s3 - 尝试使用 Lambda 从 S3 复制到 GCS 时出现 403 Access Denied
- c++ - 无法从 .hpp 文件中的类获取返回数据
- windows - Curl 在 Windows Powershell 上的行为不一致
- android - Volley / HttpURLConnection 不遵循 307/308 POST 重定向
- next.js - 如何在vercel上部署自定义github分支
- node.js - Express.Js 如何保护用户之间的资源
- c++ - AWS SDK - 没有这样的文件或目录
- spring - Spring Webflux:多次有效地使用 Flux 和/或 Mono 流(可能吗?)
- airflow - Airflow:如何使用 KubernetesExecutor 发送 email_on_failure?
- flutter - 如何使用 imagepicker 库从图库中挑选视频