我正在构建我的第一个 MVC 应用程序,并遵循了“NerdDinner”教程。但是,在以相同方式从 SelectList 创建下拉列表时,我遇到了问题。
出于某种原因,当我打开“编辑”视图时,下拉列表未显示正确的选择,即使数据在数据库中以其他方式设置并且“详细信息”视图显示了正确的值。每个人都只是想出列表中的第一个值。
我已经逐段浏览了 NerdDinner 代码,但我一生都看不到任何区别,但是该应用程序将在编辑时正确显示带有当前值的下拉列表,而我的却没有。
有人对从这里去哪里有建议吗?如果有人要求特定的东西,我可以发布代码片段。
更新:
在字段集中:
<p>
<label for="Parking">Parking Arrangement:</label>
<%= Html.DropDownList("Parking", Model.Parking)%>
<%= Html.ValidationMessage("Parking", "*") %>
</p>
编辑动作:
//
// GET: /Buyer/Edit/2
public ActionResult Edit(int id)
{
Buyer_Profile buyer_profile = buyerRepository.GetBuyerProfileByID(id);
if (buyer_profile == null)
return View("NotFound");
else if (!buyer_profile.IsOwnedBy(User.Identity.Name, id))
return RedirectToAction("Index", "Home");
else
return View(new BuyerFormViewModel(buyer_profile));
}
以他们为 NerdDinner 示例构建它的相同方式,我创建了一个“...FormViewModel”:
public class BuyerFormViewModel
{
// Properties
public Buyer_Profile Buyer_Profile { get; private set; }
public SelectList Parking { get; private set; }
// Constructor
public BuyerFormViewModel(Buyer_Profile buyer_profile)
{
Buyer_Profile = buyer_profile;
Parking = new SelectList(BuyerProfileOptions.Parking, Buyer_Profile.Parking);
}
}
当值已显示在详细信息视图中并存储在 d/b 中时,单击“编辑”时生成的 HTML:
<p>
<label for="Parking">Parking Arrangement:</label>
<select id="Parking" name="Parking"><option>No Preference</option>
<option>On Street</option>
<option>Assigned Street</option>
<option>Open Garage</option>
<option>Covered Garage</option>
</select>
</p>
相同表单中的文本字段的值已正确填充。只是所有的下拉菜单都没有!
非常感谢您的关注。