我是 MVC 4 的新手,所以这可能是新手的错误。我无法将下拉列表绑定到我的模型。我正在尝试显示用户使用 DropDownListFor 从下拉列表中所做的选择。请参阅以下代码:
CostsPerSqFoot 模型:
public class CostsPerSqFoot
{
public List<Prices> RatesList { get; set; }
public CostsPerSqFoot()
{
RatesList = new List<Prices>()
{
new Prices() {Id = 1, Rate = 1.00m},
new Prices() {Id = 2, Rate = 2.00m},
new Prices() {Id = 3, Rate = 5.00m},
new Prices() {Id = 4, Rate = 10.00m}
};
}
}
价格型号:
public class Prices
{
public int? Id { get; set; }
public decimal? Rate { get; set; }
}
CostDetails 模型(我在其中创建 SelectListItem 列表):
public class CostDetails
{
public int? Id { get; set; }
public Measurements Measurements { get; set; }
public List<SelectListItem> Costs { get; set; }
public CostDetails()
{
}
public CostDetails(List<Prices> rates)
{
Costs = new List<SelectListItem>();
foreach (var rate in rates)
{
Costs.Add(new SelectListItem()
{
Text =string.Format("{0:c}", rate.Rate), Value = rate.Id.ToString()
});
}
}
}
这是我的控制器 ActionResult 方法:
public ActionResult Index()
{
var rates = new CostsPerSqFoot();
var model = new CostDetails(rates.RatesList);
return View(model);
}
[HttpPost]
public ActionResult Calculations(CostDetails model)
{
if (ModelState.IsValid)
return View(model);
else
return View("Index", model);
}
在我的 Index 视图中,我有以下包含下拉列表的表单,并且该视图正在使用 CostDetails 模型:
@model FlooringCalculatorMVC.Models.CostDetails
// a few lines of HTML
@using (Html.BeginForm("Calculations", "Home", FormMethod.Post))
{
@Html.ValidationSummary()
@Html.LabelFor(m => m.Measurements.Length)
@Html.TextBoxFor(m =>m.Measurements.Length, new {placeholder = "Enter length"})
<br/>
<br/>
@Html.LabelFor(m => m.Measurements.Width)
@Html.TextBoxFor(m =>m.Measurements.Width, new {placeholder = "Enter width"})
<br/>
<br/>
@Html.LabelFor(m => m.Costs)
@Html.DropDownListFor(m =>m.Id, Model.Costs, "- Select a rate -")
<button type="submit">Calculate</button>
}
最后,我只想显示用户在单击“提交”时所做的选定下拉选项。在“计算”视图中,我只有以下内容:
@model FlooringCalculatorMVC.Models.CostDetails
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Calculations</title>
</head>
<body>
<div>
@Model.Costs
</div>
</body>
</html>
我可能做错了什么?提前致谢。