[英]Filter my @html.dropdownlistfor
我正在處理一個項目,我需要根據我的第一個dropdownlistfor值過濾第二個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");
好的,所以您有一個控制器,該控制器的方法可以為您提供經過過濾的項目,如下所示:
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));
});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.