3

我正在构建我的第一个 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>

相同表单中的文本字段的值已正确填充。只是所有的下拉菜单都没有!

非常感谢您的关注。

4

2 回答 2

2

嗯。看来 htmlhelper 太好了。我删除了对模型的引用,一切正常!

IE

 <%= Html.DropDownList("Parking", Model.Parking)%>

变成

 <%= Html.DropDownList("Parking")%>

我们是金色的。ViewData 是否包含称为“停车”的东西,因为我在模型中引用它,所以它压扁了另一个值......或什么......?

于 2009-05-10T02:59:00.220 回答
2

给人们的快速提示 - 当他们需要下拉列表时,不要将任何模型属性命名为“标题”。该框架将与视图标题混淆并且无法工作 - 我花了整整一个下午的时间来解决这个问题。需要睡在上面才能意识到发生了什么。

于 2011-01-14T09:53:52.810 回答