我是MVC 4的新手,所以這可能是一個新手的錯誤。我無法將我的下拉列表綁定到我的模型。我正嘗試使用DropDownListFor顯示用戶從下拉列表中選擇的選擇。請看下面的代碼:MVC 4 - 使用ID的Dropdownlist - 檢索回傳值
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>
我該做什麼錯?提前致謝。
Model.Costs是列表。在DropDownListFor中,您正在將所選項目嘗試到id字段。如果你想看到選定的項目,你需要看看該領域 –
感謝您的答案。但我該怎麼做?如果我在「計算」視圖上嘗試@ Html.DisplayFor(m => m.Id),它將顯示Id值,而不是從下拉列表中選擇的值。 – user2913657