在IF语句MVC中使用Dropdownlist选择的值

时间:2015-03-02 06:27:31

标签: asp.net-mvc asp.net-mvc-4

我是MVC的新手。我正在尝试ASP.NET MVC 4中的Cascading Dropdownlist。我的问题是我想在@foreach循环中访问所选的countryid

@Html.DropDownList("ddlCountry", new SelectList(@Model.Countries, "CountryId", "CountryName"))


$("#ddlCountry").change(function () {
        @foreach (var item in @Model.States.Select(x=>x.countryId = ?))
        {

        }
});

如何用countryId替换上面的问号,以便我可以过滤状态

先谢谢

由于

SRRIN

3 个答案:

答案 0 :(得分:0)

您可以通过此

获取jquery中的值
$("#ddlCountry option:selected").text();

正如@Stephen所说,你无法使用剃刀获得所选选项的价值。因为剃刀代码是在页面加载之前执行的。

解决方法是

$("#ddlCountry").change(function () {
 var selectedVal= $("#ddlCountry option:selected").text();
 var list = @Model.States.Tojson();

});

然后使用inArray进行进一步的操作

答案 1 :(得分:0)

感谢所有人。 正如Stephen和Nikitesh所说,在razor脚本中无法访问javascript变量。所以我成功地采用了以下方法。

var selectedCountryId = $("#ddlCountry").val();
var states = @Html.Raw(Json.Encode(Model.States));
for (var i = 0; i < states .length; i++) {
if (states [i].countryid == selectedCountryId ) {
... populate states here
}
}

由于

SRRIN

答案 2 :(得分:-1)

您可以使用下拉列表选择值并将查询传递为:

@Html.DropDownList("ddlCountry", new SelectList(@Model.Countries,"CountryId", "CountryName"))
$("#ddlCountry").change(function () {
var countryId=parseInt($(this).val());
    @foreach (var item in @Model.States.Select(x=>x.countryId = countryId))
    {

    }
});