我是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);
}
在我的索引视图中,我有以下包含下拉列表的表单,并且视图使用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>
我可能做错了什么?提前谢谢。
答案 0 :(得分:0)
如果Id是记录ID,我会在模型中创建一个选定的字段。然后你可以做类似
的事情@Html.DropDownListFor(x => x.Selected, Model.Costs).
将使用所选记录的值填充所选字段。如果您想要所选文本,则可以查询Model.Costs或使用jquery。