2012-05-11 80 views
1

我有編輯窗體的MVC3網站。在這個表單中有DropDownList,它顯示了可以選擇的值列表。我希望它被設置爲先前選定的值(在創建表單上)。該值在Model.Status中。我認爲這個代碼可以工作:DropDownList - 編輯表單中顯示的選定值

@Html.DropDownList("Status", 
      new SelectList(ViewBag.Status as System.Collections.IEnumerable, "Id", "Status", Model.Status)) 

但DropDownList總是設置在列表中的第一個值。我已檢查 - 正確的值在Model.StatusModel.Status的值是來自列表的狀態ID。 ViewBag.Status是一個ID和字符串描述 - 狀態的列表。

如何讓它顯示正確的值? 任何幫助非常感謝!

+0

我想你應該覆蓋的類型「狀態」平等法,如果Model.Status不是ViewBag.Status的要素之一。 –

回答

3

你檢查this bug

避免使用DropDownListSelectList相同的名稱。

+0

你說得對 - 那是問題所在。我已經嘗試了很多不同的解決方案,但我甚至沒有想過這是一個問題! – Marta

1
@Html.DropDownListFor(x=>x.SelectedItemId, 
        new SelectList(ViewBag.Status as System.Collections.IEnumerable,"Id", 
        "Status"),"Select Item") 

,但如果我寫這段代碼,我會擺脫ViewBag和改變使用另一個強類型的對象

public class YourMainViewModel 
{ 
    public int ID { set;get;} 

    public int SelectedItemId { set;get;} 
    public IEnumerable<Item> Items(); 
    //other properties 
} 

public class Item 
{ 
    public int Id { set;get;} 
    public string Status { set;get;} 
} 

而是在Viewbag發送收集的,我會用我的新模型屬性現在

public ActionResult EditUser(int id) 
{ 
    var user=myRepositary.GetUser(id); 
    user.Items=myRepositary.GetAllItems(); 
    user.SelectedItemId=5; // replace with the value from your database here, 
} 

現在在我看來,這是強類型到YourMainViewModel,我會寫這個

@Html.DropDownListFor(x=>x.SelectedItemId, 
        new SelectList(Model.Items,"Id", 
        "Status"),"Select Item") 
0

以下是一些示例代碼,您可以在您的方案中進行修改和使用。我有一個編輯視圖,在這個視圖中是下拉列表中的銀行列表,並且與該應用程序關聯的銀行已經在列表中預選。

我的觀點:

@model MyProject.ViewModels.MyViewModel 

我的銀行下拉:

<td><b>Bank:</b></td> 
<td> 
    @Html.DropDownListFor(
      x => x.BankId, 
      new SelectList(Model.Banks, "Id", "Name", Model.BankId), 
      "-- Select --" 
    ) 
    @Html.ValidationMessageFor(x => x.BankId) 
</td> 

我MyViewModel:

public class MyViewModel 
{ 
    // Partial class 

    public int BankId { get; set; } 
    public IEnumerable<Bank> Banks { get; set; } 
} 

我的編輯操作方法:

public ActionResult Edit(int id) 
{ 
    // Get the required application 
    GrantApplication application = grantApplicationService.FindById(id); 

    // Mapping 
    MyViewModel viewModel = (MyViewModel) 
      grantApplicationMapper.Map(
      application, 
      typeof(GrantApplication), 
      typeof(MyViewModel) 
    ); 

    // BankId comes from my table. This is the unique identifier for the bank that was selected when the application was added 

    // Get all the banks 
    viewModel.Banks = bankService.FindAll().Where(x => x.IsActive); 

    return View(viewModel); 
} 

我的銀行類:

public class Bank 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public bool IsActive { get; set; } 
} 

做它的形式加載後這種方式會在你的下拉菜單選擇的值。

我希望這有助於:)

相關問題