2009-05-06 53 views
3

我正在構建我的第一個MVC應用程序,並遵循'NerdDinner'教程。但是,在以同樣的方式從SelectList創建下拉列表時,我遇到了一個問題。mvc - dropdownlist沒有在編輯視圖中正確填充

出於某種原因,當我調出'編輯'視圖時,即使數據庫中的數據設置爲其他數據並且'詳細信息'視圖顯示正確的值,下拉列表也不會顯示正確的選擇。每個人都只是想出列表中的第一個值。

我已經通過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> 

以相同的形式的文本字段已它們的值正確填充。這只是所有的下拉沒有!

非常感謝您的關注。

+0

我已經經歷了一步一步的調試程序,當它完成渲染頁面時,正確的事情看起來會出來。但是......它只是沒有。 – user101306 2009-05-06 04:18:04

+1

您可以發佈HtmlHelper和編輯操作的代碼片段嗎? 也是HTML輸出。 – 2009-05-07 07:11:17

回答

2

呵呵。看來,htmlhelper是太好了。我刪除了對模型的引用,一切正常!

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

成爲

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

和我們的黃金。 ViewData是否包含一些名爲「Parking」的內容,是因爲我在模型中引用了它,所以它壓縮了另一個值......或者某個東西......?

1

人們的快速提示 - 當他們需要下拉列表時,不要命名您的任何模型屬性「標題」。該框架將與視圖標題混合在一起,並且不起作用 - 我花了整整一個下午把這件事撕掉。需要睡覺才能意識到發生了什麼。