我正在使用一个项目,我需要根据我的第一个dropdownlistfor过滤我的第二个下拉列表。它很容易理解,但很难编码,因为我不知道jquery或javascript和我在mvc asp.net中工作,以及在数据所在的sql server中使用数据库。
我需要根据客户的下拉列表来过滤项目的下拉列表。
这里有一些代码:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>TimeEntry</legend>
<div class="editor-label">
@Html.Label("Customer")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.TimeEntry.CustomerId, @customerSelectList)
@Html.ValidationMessageFor(model => model.TimeEntry.CustomerId)
</div>
<div class="editor-label">
@Html.Label("Project")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.TimeEntry.ProjectId, @projectSelectList, "[ - No project - ]")
@Html.ValidationMessageFor(model => model.TimeEntry.ProjectId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
public IEnumerable<Customer> Customers { get; set; }
public IEnumerable<Project> Projects { get; set; }
这是一个代码,我认为是从数据库调用但不确定的代码:
var customers = service.GetAllCustomers().ToList();
model.Customers = new SelectList(customers, "CustomerId", "Name");
var projects = service.GetAllProjects().ToList();
model.Projects = new SelectList(projects, "ProjectId", "Name");
答案 0 :(得分:0)
好的,所以你有一个控制器,它有一个方法可以为你提供过滤项目:
public class FilterController:Controller {
public ActionResult Projects(int customerId) {
// I expect this call to be filtered
// so I'll leave this to you on how you want this filtered
var projects = service.GetAllProjects().ToList();
// at this point, projects should already be filtered with "customerId"
return Json(new SelectList(projects, "ProjectId", "Name"),
JsonRequestBehavior.AllowGet);
}
}
然后在客户端上调用该方法,如下所示:
// when the customer dropdown changes, you want to use the selected value
// and filter the projects dropdown - more like refresh it
$("#TimeEntry_CustomerId").change(function(){
refreshProjects($(this).val());
});
function refreshProjects(id) {
var projects = $("#TimeEntry_ProjectId");
$.get('@Url.Action("projects","filter")', {customerId:id},
function (result) {
// clear the dropdown
projects.empty();
// rebuild the dropdown
$.each(result, function (i, e) {
projects.append($('<option/>').text(e.Text).val(e.Value));
});
});
}