将数据从HTTP POST create方法传递到使用AJAX查看

时间:2017-09-25 00:45:12

标签: c# asp.net-mvc

我想根据用户选择的国家/地区过滤机场列表。我只想展示这个国家的机场。我有一个视图,我在显示两个下拉列表:

@using WebApplication1.Models
@using WebApplication1.Controllers
@model Country

@{
ViewBag.Title = "Index";
}

@using (Html.BeginForm())
{
<h2>Airport List</h2>
@Html.Label("Airports", "Airports")
<select name="Airports">
    @foreach (var airport in ViewBag.EuropeanAirports)
    {
    <option value="@(airport.name)">@(airport.name)</option>
    }
</select>

@Html.Label("Country", "Country")


@Html.DropDownListFor(c =>c.country, new SelectList(ViewBag.countries, "country", "country"), "Select Country")

}

以下是我的控制器中的代码,我使用create方法来获取下拉列表,我正在使用帖子来检索用户选择的国家/地区。我使用LINQ查询来检索一个国家/地区中的给定机场,因为我有两个JSON文件,一个用于国家/地区列表,另一个用于机场列表。这是我在控制器中的代码:         //获取方法        public ActionResult Create()         {

        //LINQ QUERY TO RETRIEVE ALL EUROPEAN AIRPORTS 
        IEnumerable<Airport> EuropeanAirports = from n in airports
                       where n.continent.Equals("EU")
                       select n;
        IEnumerable<Country> countries = GetCountries();
        ViewBag.countries = countries;
        ViewBag.EuropeanAirports = EuropeanAirports; 
        return View(new Country());
    }

    [HttpPost]
    public ActionResult Create(Country postedCountry)
    {
        IEnumerable<Country> countries = GetCountries();
        string selectedCountry = postedCountry.country;
        var abbreviation = from n in countries
                           where n.country.Equals(selectedCountry)
                           select n.abbr;
        IEnumerable<Airport> EuropeanAirports = from n in airports
                                                where 
                                       n.iso.Equals(abbreviation)
                                                select n;
        ViewBag.EuropeanAirports = EuropeanAirports;
        return View(EuropeanAirports);
    }

以下是我正在处理的JSON文件:

国家/地区JSON文件:      [

 {
"country": "Iceland",
"abbr": "IS"
},
{
"country": "Kosovo",
"abbr": "KS"
},
...
]

机场JSON:

  [
  {
    "iata": "UTK",
    "lon": "169.86667",
    "iso": "MH",
    "status": 1,
    "name": "Utirik Airport",
    "continent": "OC",
    "type": "airport",
    "lat": "11.233333",
    "size": "small"
  },
...
  ]

我的目标是根据最终用户选择的国家/地区过滤机场下拉列表的内容。从您的控制器可以看出,我已经尝试获取特定于该国家/地区的机场列表,但我真的不知道如何将该信息传输到视图并更新机场下拉列表的内容。我想我必须使用AJAX来做到这一点,我并不熟悉它。我正在我的控制器中创建方法的HTTP POST中对机场进行所有过滤,我不知道这是否合法,我不知道如何在我的视图中检索所有信息并填充我的下拉列表列表。

1 个答案:

答案 0 :(得分:0)

如果您只想在所选国家/地区更改时更改下拉列表(选择列表)值,那么您确实需要良好的旧ajax。这是一个简单的JQUERY实现。

查看模特:

public class CreateViewModel
{
    IEnumerable<Country> Countries { get; set; }
    IEnumerable<Airport> Airports { get; set; }

    public CreateViewModel() {}
} 

控制器:

[HttpGet]
public ActionResult Create()
{   
    //LINQ QUERY TO RETRIEVE ALL EUROPEAN AIRPORTS 
    IEnumerable<Airport> europeanAirports = from n in airports
                   where n.continent.Equals("EU")
                   select n;
    IEnumerable<Country> countries = GetCountries();

    CreateViewModel viewModel = new CreateViewModel();
    viewModel.Countries = countries;
    viewModel.Airports = europeanAirports;

    return View(viewModel);
}

[HttpGet]
public ActionResult GetCountryAirports(string countryCode)
{
    // Get the airports you need
    IEnumerable<Airport> airports = null;

    return Json(airports, JsonRequestBehavior.AllowGet);
}

查看:

@using WebApplication1.Models
@using WebApplication1.Controllers
@model Country

@{
ViewBag.Title = "Index";
}

@using (Html.BeginForm()) // Do not know what this is for
{
    <h2>Airport List</h2>
    @Html.Label("Airports", "Airports")
    @Html.DropDownList("Airports", new SelectList(Model.Airports, "id", "name"), new { @class = "form-control" }) // id is the value when selected, name is the text displayed. Change as needed.
    @Html.Label("Country", "Country")
    @Html.DropDownList("Country", new SelectList(Model.Countries, "id", "name"), "Select Country", new { @class = "form-control" }) // id is the value when selected, name is the text displayed. Change as needed.
}

<script type="text/javascript">
$(document).ready(function(){
    $("#Country").change(function(){
        var countryId = $(this).val();
        $.ajax({
            url: '@Url.Action("GetCountryAirports", "Action")',
            type: 'GET',
            data: {
                countryId: countryId
            },
            success: function (data) {
                var markup = "";

                // markup += "<option value=''></option>"; Uncomment if you want to add a blank option

                for (var i = 0; i < data.length; i++) {
                    markup += "<option value=" + data[i].id + ">" + data[i].name + "</option>"; // Change id and name to correct properties
                }

                $("#Airports").html(markup).show();
            },
            error: function (error) {
                $("#Airports").empty();
                $("#Airports").val('');
            }
        });
    });
});
</script>