当下拉列表似乎更合适时,这当然是一个奇怪的要求,但我们之前都有过奇怪的要求。:) 这是一个简单的例子,希望能展示你需要知道的一切,以便让它工作。
首先,一个将国家名称与 id 关联起来的简单模型:
public class CountryModel
{
public int Id { get; set; }
public string Country { get; set; }
}
现在控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string country)
{
var countryId = GetCountries()
.Where(c => c.Country.ToLower() == country.ToLower())
.Select(c => c.Id)
.SingleOrDefault();
if (countryId != 0)
return RedirectToAction("Thanks");
else
ModelState.AddModelError("CountryNotSelected", "You have selected an invalid country.");
return View();
}
private List<CountryModel> GetCountries()
{
return new List<CountryModel>
{
new CountryModel { Id = 1, Country = "Russia" },
new CountryModel { Id = 2, Country = "USA" },
new CountryModel { Id = 3, Country = "Germany" }
};
}
}
这是视图:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(false)
<fieldset>
<div class="editor-field">
@Html.TextBox("Country")
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
这里有几点需要注意。首先,您已经声明您在此视图中有额外的属性。在这种情况下,我会将它们放在一个CountryViewModel
和模型中绑定到 HTTP POST 方法中的一个实例,而不是简单地绑定到一个字符串。所以,像这样:
public class CountryViewModel
{
public string SomeValue { get; set; }
public string SomeMoreFormData { get; set; }
public string Country { get; set; }
}
然后从这里开始,POST 方法会变成这样:
[HttpPost]
public ActionResult Index(CountryViewModel viewModel)
{
var countryId = GetCountries()
.Where(c => c.Country.ToLower() == viewModel.Country.ToLower())
.Select(c => c.Id)
.SingleOrDefault();
if (countryId != 0)
return RedirectToAction("Thanks");
else
ModelState.AddModelError("CountryNotSelected", "You have selected an invalid country.");
return View(viewModel);
}
其次,请注意我是如何通过GetCountries()
. 如果您的需求发生变化,这将允许您稍后轻松地重构它以从数据库中获取国家/地区列表。