簡體   English   中英

將下拉列表中選擇的值從視圖傳遞到控制器

[英]Pass value selected in drop down list from view to controller

我試圖將用戶從視圖的下拉列表“ COUNTRY”中選擇的值傳遞給控制器​​,我嘗試通過HTTP POST方法檢索它,但未成功。 這是我的看法的代碼:

@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")

}

這是我的控制器:

public class AirportController : Controller
{
    // GET: HelloWorld
    public ActionResult Create()
    {
        IEnumerable<Airport> airports = GetAirports();
        //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());
    }

這是我的國家/地區模型:

public class Country
{
    public string country { get; set; }
    public string abbr { get; set; }
}

同樣,我的目標是從國家/地區下拉列表中檢索用戶選擇的值。 我不知道是否應添加用於創建的post方法,並且不知道如何將所選值從視圖傳遞到控制器。

默認情況下,HTML Helper表單將發布到同一控制器操作。 您可以像這樣使用HttpPost方法屬性聲明它

[HttpPost]
public ActionResult Create(Country postedCountry)
{

    string selectedCountry = postedCountry.country

}

如您所見,發布的對象將與您傳遞給視圖的模型相同,並且其屬性將由用戶發布的表單選擇決定

  [HttpGet]
  public ActionResult Create()
    {
        IEnumerable<Airport> airports = GetAirports();
        //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(string country)
        {
         if (ModelState.IsValid)//if theres not errors
            {
               //Add your save Funcation Here
               //db.Countries.Add(country)
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View();//if there is errors display the same view
        }

如果您需要保存Airport ddl,只需將ddl的名稱添加到控制器中,如下所示

 public ActionResult Create(string country,string Airports)

希望這個幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM