1

私はプロジェクトで作業しており、最初のドロップダウンリストの値に基づいて2番目のドロップダウンリストをフィルタリングする必要があります。jqueryまたはjavascriptを知らず、mvc asp.netで作業しているだけでなく、データが配置されているSQLサーバーでデータベースを使用しているため、理解するのは簡単ですが、コーディングするのは困難です。

顧客のドロップダウンに基づいて、プロジェクトのドロップダウンをフィルタリングする必要があります。

コードの一部を次に示します。

@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");
4

1 に答える 1

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));
            });                
    });            
}
于 2013-04-30T08:33:19.730 に答える