gpt4 book ai didi

javascript - 过滤我的@html.dropdownlist

转载 作者:行者123 更新时间:2023-11-28 09:11:14 25 4
gpt4 key购买 nike

我正在处理一个项目,我需要根据我的第一个下拉列表值过滤我的第二个下拉列表。它很容易理解,但很难编码,因为我不知道 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");

最佳答案

好吧,你有一个 Controller ,它的方法可以为你提供过滤后的项目,如下所示:

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));
});
});
}

关于javascript - 过滤我的@html.dropdownlist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16294914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com