【问题标题】:Correct way to define Model class, and Dropdown Selected Index change定义模型类的正确方法和下拉选定索引更改
【发布时间】:2014-01-02 19:49:51
【问题描述】:

我必须为国家绑定一个下拉列表,选择国家后,状态应该自动填充到第二个下拉列表中。

我已经通过以下方式定义了模型类。

public class Country
{
    public string Code { get; set; }
    public string Name { get; set; }
}

public class State
{
    public string Code { get; set; }
    public string Name { get; set; }
    public Country CountryName { get; set; }
}

第一季度。这是定义模型类的正确方法吗?

在这之后我有一个看法

  @Html.DropDownListFor(Model => Model.Country,new SelectList(ViewBag.Countries,"Code","Name"))

第二季度。我应该如何以及在哪里编写代码来获取所选国家的状态。 (当国家代码作为参数传递时,我有一种获取状态的方法)

public List<State> GetStates(string CountryCode)

【问题讨论】:

标签: c# asp.net asp.net-mvc-4 razor


【解决方案1】:

第一季度: 尽管我会更改以下内容,但您的模型看起来是正确的:

public Country CountryName { get; set; }

public Country Country { get; set; }

为了更好的可读性。

第二季度: 一种方法是编写一个控制器操作,以基于 JSON 格式的国家代码返回一个状态列表,并在选择一个国家/地区时通过 AJAX 调用此控制器操作。

控制器动作:

public ActionResult GetStates(string countryCode)
{
    var states = _statesService.GetStatesByCountry(countryCode)
                     .OrderBy(x => x.Name.ToUpper());

    return Json(states.Select(x => new { value = x.Code, text = x.Name }));
}

Javascript:

$("#countryDropdownId").on("change", function () {
    var countryCode = $("#countryDropdownId option:selected").val();

    $.getJSON(
        "@Url.Action("GetStates")", 
        { countryCode: countryCode },
        function (states) {
            var statesDropdown = $("#statesDropdownId");

            statesDropdown.empty();

            $.each(states, function(index, state) {
                statesDropdown.append($("<option />", {
                    value: state.value,
                    text: state.text
                }));
            });
        }
    );
});

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多