【问题标题】:mvc - dropdownlist not populating correctly within Edit viewmvc - 下拉列表未在编辑视图中正确填充
【发布时间】:2009-05-06 04:15:56
【问题描述】:

我正在构建我的第一个 MVC 应用程序,并遵循了“NerdDinner”教程。但是,在以相同方式从 SelectList 创建下拉列表时,我遇到了问题。

由于某种原因,当我打开“编辑”视图时,下拉列表未显示正确的选择,即使数据在数据库中以其他方式设置并且“详细信息”视图显示了正确的值。每个人都只是想出列表中的第一个值。

我已经逐段浏览了 NerdDinner 代码,我一生都看不出有任何区别,但该应用程序会在编辑时正确显示带有当前值的下拉列表,而我的则不会。

有人对从这里去哪里有建议吗?如果有人要求特定的东西,我可以发布代码 sn-ps。

更新:

在字段集中:

        <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>

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

非常感谢您的关注。

【问题讨论】:

  • 我已经逐步完成了调试器,当它完成呈现页面时,正确的东西看起来会出来。但是......它只是没有。
  • 你能发布 HtmlHelper 和 Edit 操作的 sn-p。还有 HTML 输出。

标签: asp.net-mvc selectlist


【解决方案1】:

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

即

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

变成

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

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

【讨论】:

  • 下拉列表的第二个参数是选择的值,您可能已经强类型化了您的视图,因此模型是您的视图模型,因此通过执行 Model.Parking 停车属性实际上是您的选择列表object.. 就好像你在哪里做 model.Buyer_Profile.Parking 一样也可以工作。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多