1

我正在與一個項目合作,我需要根據我的第一個dropdownlistfor value來過濾我的第二個dropdownlist。它很容易理解,但很難編碼它,因爲我不知道jquery或javascript,我在mvc asp.net工作,以及在數據庫所在的sql server中使用數據庫。過濾我的@ html.dropdownlistfor

我需要根據客戶的下拉列表篩選項目的下拉菜單。

這裏是一些代碼:

@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

第二個下拉菜單的lisitems來自哪裏?你打算調用一個控制器方法(這隻有意義)? – 2013-04-30 07:58:16

+0

@von v忘記了模型的代碼,現在更新了 – user2043267 2013-04-30 08:01:43

+0

恐怕沒有幫助。你打算如何做過濾?通過一些Ajax調用權?所以你可以有一個控制器方法,聲明'GetProjects'接受'customerId'的一個int,然後你查詢你的數據庫並返回一個你可以在客戶端上使用的json結果並且構建你的項目下拉列表,這和方法類似你在想什麼? – 2013-04-30 08:04:45

回答

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

vive的調用一直在看着它,並嘗試不同的解決方案,但我不能讓它工作。我們並不真正瞭解該功能的工作方式,因此我們正在考慮退出該問題並將此代碼發送給我們的suporvisor,但感謝您的幫助 – user2043267 2013-04-30 09:32:05