2017-09-24 76 views
0

我想傳遞一個值,用戶從下拉列表中選擇「國家」從視圖到控制器,我試圖通過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方法來創建,我不知道如何將選定的值從視圖傳遞給控制器​​。

回答

0

默認情況下,Html Helper表單將發佈到相同的控制器操作。你會使用類似的HttpPost方法屬性這麼

[HttpPost] 
public ActionResult Create(Country postedCountry) 
{ 

    string selectedCountry = postedCountry.country 

} 

正如你所看到的,所張貼的對象將是你傳遞給視圖相同的模型宣佈,它的性質將由形式的選擇來確定用戶發佈

0
[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 
     } 

的拼寫,如果你需要保存的名稱機場DDL 只需將ddl的名稱添加到控制器就可以了

public ActionResult Create(string country,string Airports) 

希望得到這個幫助!

相關問題