【发布时间】:2018-11-21 17:39:44
【问题描述】:
事实证明,我有一个来自级联下拉列表的 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>
【问题讨论】:
-
在控制器中,您需要获取对当前用户 (userId) 的引用,并在 linq 查询中传递该值,以便也按 userId 进行过滤
-
将
Where条件添加到您的 LINQ 查询中,以便仅为 userId 获取数据。在不知道你的数据模型架构的情况下,很难给你一个具体的答案。 -
我建议澄清您的问题/意图。您提供的信息很好,可能会像@Shyju 所说的那样添加更多关于您的数据模型架构的信息。
-
与visual-studio 无关的注释。如果您阅读说明,它会说不要在有关代码的问题上使用此标记,而这些代码恰好是用 Visual Studio 编写的。,因此不应在此问题中使用它。
-
谢谢我有这些模型用户,地区和服务,我还有另一个模型叫做发烧,用户输入患者人数和发烧患者人数,后一个模型需要地区信息和服务。在用户模型中,它需要姓名,姓氏,用户名,即电子邮件地址,还需要他们所属的地区和服务。有了这一切,我想做的是,当用户登录时,只加载用户所在地区的服务。
标签: c# jquery asp.net-mvc visual-studio