我正在尝试将用户从下拉列表“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; }
}
我的目标是再次检索用户从国家/地区下拉列表中选择的值。我不知道是否应该为create添加post方法,我不知道如何将所选值从视图传递给控制器。
答案 0 :(得分:0)
默认情况下,Html Helper表单将发布到同一个控制器操作。您可以使用HttpPost方法属性声明它,如此
[HttpPost]
public ActionResult Create(Country postedCountry)
{
string selectedCountry = postedCountry.country
}
如您所见,发布的对象将与您传递给视图的模型相同,其属性将由用户发布的表单选择确定
答案 1 :(得分: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
}
如果您需要保存Airport ddl 只需将ddl的名称添加到控制器就像这样
public ActionResult Create(string country,string Airports)
希望这个帮助!