2015-09-25 87 views
-1

我是MVC.NET 5的新手; 我正在開發一個帶下拉和表單的應用程序。我的下拉菜單是我的模型創建的,我無法找到如何從下拉菜單中選取下拉菜單。 下面是代碼的一部分:MVC 5從級聯下拉獲取值

第一下拉部分視圖:

@using System.Data.SqlClient 
@model Cars.Web.Models.TestModel 

@using (Ajax.BeginForm("GetByMake", "Cars", null, new AjaxOptions 
{ 
    HttpMethod = "POST", 
    UpdateTargetId = "models", 
    InsertionMode = InsertionMode.Replace 
}, new { id = "selectMarke" })) 
{ 
    @Html.DropDownListFor(
     m => m.SelectedMarkeId, 
     new SelectList(Model.Markes, "Id", "Name"), 
     String.Empty 
     ) 
} 

<script> 
    $('#SelectedMarkeId').change(function() { 
     console.log("asd"); 
     $('#selectMarke').submit(); 
    }); 
</script> 

這裏是第二:

@model Cars.Web.Models.TestModel 

@if (Model.Models != null && Model.Models.Any()) 
{ 
     @Html.DropDownList(
      "models", 
      new SelectList(Model.Models, "Id", "ModelName"), 
      string.Empty 
      ) 
} 

我可以從firstone ID傳遞給第二個形成控制器,但我認爲,這不是正確的方法。我想知道如果我添加更多的表單,如何在提交時將這兩個表單綁定在一起。 感謝

+0

這可能是有益的http://stackoverflow.com/questions/22952196/cascading-dropdown-lists-in-asp-net-mvc-5/30945495#30945495 –

回答

0

當你使用:

@Html.DropDownListFor(
     m => m.SelectedMarkeId, 
     new SelectList(Model.Markes, "Id", "Name"), 
     String.Empty 
     ) 

的下拉列表的name將是 「SelectedMarkeId」。

當你使用:

@Html.DropDownList(
      "models", 
      new SelectList(Model.Models, "Id", "ModelName"), 
      string.Empty 
      ) 

的下拉列表的name將是「模特」

的控制器必須與輸入端的name匹配的一個參數。像這樣:

[HttpPost] 
public ActionResult SomeAction (int models, int SelectedMarkeId) 
{ 
    //SelectedMarkeId is the selected value of the first drop down list 
    //models is the selected value of the second drop down list 
    //your code here 
} 

您還可以使用一個對象,其中包含與輸入名稱匹配的屬性。像這樣:

public class TestModel 
{ 
    public int models { get; set; } 
    public int SelectedMarkeId { get; set; } 
} 

[HttpPost] 
public ActionResult SomeAction (TestModel model) 
{ 
    //SelectedMarkeId is the selected value of the first drop down list 
    //models is the selected value of the second drop down list 
    //your code here 
} 
+0

工作就像一個魅力 –

+0

不要忘記將帖子標記爲答案,這樣你可以幫助未來的人 –