2015-09-25 82 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

不要忘记将帖子标记为答案,这样你可以帮助未来的人 –