首页 > 解决方案 > 使用用户修改 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>

标签: c#jqueryasp.net-mvcvisual-studio

解决方案


假设登录的用户正在使用控制器方法。您可以获取用户并通过他的地区 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);
}

推荐阅读