2012-04-06 114 views
17

我試圖尋找,並沒有發現任何固定我的問題。我在Razor視圖上有一個DropDownList,它不會顯示我在SelectList中標記爲Selected的項目。下面是填充列表的控制器代碼:MVC的DropDownList的SelectedValue不正確顯示

var statuses = new SelectList(db.OrderStatuses, "ID", "Name", order.Status.ID.ToString()); 
ViewBag.Statuses = statuses; 
return View(vm); 

這裏是查看代碼:

<div class="display-label"> 
    Order Status</div> 
<div class="editor-field"> 
    @Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses) 
    @Html.ValidationMessageFor(model => model.StatusID) 
</div> 

我通過它,甚至在視圖中走它具有正確的SelectedValue但是DDL總是顯示不管選擇的值如何,列表中的第一項。任何人都可以指出我做錯了什麼使DDL默認爲SelectValue?

+0

請參閱下面的鏈接。 http://stackoverflow.com/questions/5188563/asp-net-mvc-drop-down-list-selection-partial-views-and-model-binding – 2012-04-06 04:42:17

+0

alok_dida,我看了一下,它看起來很除了在構造SelectList時選擇的值使用整個對象與ID.ToString()像我在做的一樣。然而,我改變了我的代碼做同樣的事情,並沒有解決問題。兩者之間有一些差異,我錯過了可以解決我的問題嗎? – azorr 2012-04-06 04:48:55

+1

我添加了一個如何完成的詳細示例。 – 2012-04-06 13:23:43

回答

40

SelectList構造(在其中您希望能夠通過所選擇的值id)的最後一個參數,因爲DropDownListFor助手使用您作爲第一個參數傳遞lambda表達式,並使用特定屬性的值將被忽略。

因此,這裏的醜陋的方式做到這一點:

型號:

public class MyModel 
{ 
    public int StatusID { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     // TODO: obviously this comes from your DB, 
     // but I hate showing code on SO that people are 
     // not able to compile and play with because it has 
     // gazzilion of external dependencies 
     var statuses = new SelectList(
      new[] 
      { 
       new { ID = 1, Name = "status 1" }, 
       new { ID = 2, Name = "status 2" }, 
       new { ID = 3, Name = "status 3" }, 
       new { ID = 4, Name = "status 4" }, 
      }, 
      "ID", 
      "Name" 
     ); 
     ViewBag.Statuses = statuses; 

     var model = new MyModel(); 
     model.StatusID = 3; // preselect the element with ID=3 in the list 
     return View(model); 
    } 
} 

查看:

@model MyModel 
...  
@Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses) 

,這裏是正確的方法,用真實的視圖模型:

型號

public class MyModel 
{ 
    public int StatusID { get; set; } 
    public IEnumerable<SelectListItem> Statuses { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     // TODO: obviously this comes from your DB, 
     // but I hate showing code on SO that people are 
     // not able to compile and play with because it has 
     // gazzilion of external dependencies 
     var statuses = new SelectList(
      new[] 
      { 
       new { ID = 1, Name = "status 1" }, 
       new { ID = 2, Name = "status 2" }, 
       new { ID = 3, Name = "status 3" }, 
       new { ID = 4, Name = "status 4" }, 
      }, 
      "ID", 
      "Name" 
     ); 
     var model = new MyModel(); 
     model.Statuses = statuses; 
     model.StatusID = 3; // preselect the element with ID=3 in the list 
     return View(model); 
    } 
} 

查看:

@model MyModel 
...  
@Html.DropDownListFor(model => model.StatusID, Model.Statuses) 
+0

優秀的答案,謝謝你解釋這個問題,並舉例說明如何解決這個問題。感謝您的幫助。 – azorr 2012-04-07 18:48:31

+0

我真的不知道StatusID綁定在哪裏? 「SelectList」的第四個值不是選定的值嗎?你實際上沒有告訴選擇列表嗎?它只是知道我還是瘋了嗎?我不能得到這個工作來預選很多下拉菜單:( – ppumkin 2013-06-06 12:26:01

+2

@ppumkin,不,當你使用視圖模型和強類型助手時,你不需要SelectList構造函數的第四個參數,這就是'x => x.StatusID '順便說一下,從我的示例中可以看到,我甚至沒有使用SelectList構造函數,因爲我的視圖模型屬性是IEnumerable ',可以直接綁定到DropDownListFor。 – 2013-06-06 13:37:18

-3

請從下面的示例代碼。

public class Temp 
    { 
     public int id { get; set; } 
     public string valueString { get; set; } 
    } 

控制器

public ActionResult Index() 
     { 
      // Assuming here that you have written a method which will return the list of Temp objects. 
      List<Temp> temps = GetList(); 

      var tempData = new SelectList(temps, "id", "valueString",3); 
      ViewBag.Statuses = tempData; 

      return View(); 
     } 

查看

@Html.DropDownListFor(model => model.id, (SelectList)ViewBag.Statuses) 
    @Html.ValidationMessageFor(model => model.id) 
+5

我的眼睛正在燃燒...... aaaaaaaaaaa ..那是什麼? – ppumkin 2013-06-06 12:22:35

+0

我希望你只是從一些示例代碼中複製並粘貼了這段代碼。這可以很容易地在for循環中完成。對不起,代碼納粹,但老實說,我們應該停止傳播壞代碼,即使不使用生產代碼。除非你介紹編程這是一個完全不同的層次。 – pqsk 2014-04-29 16:37:47

+0

夥計們,這只是一個例子。用戶可以創建一個列表。我創建了一張清單,這對他來說沒有任何意義,因爲他將擁有自己的收藏。從他那裏來的線是來自C#的最後2行代碼和來自HTML的2行代碼。請不要在沒有邏輯的情況下降低代碼。您也可以編輯帖子。如果答案不正確,可以降低評分。這段代碼中有什麼錯誤? – 2017-12-26 10:20:55

2

爲每個視圖創建一個視圖模型。這樣做,你將只包括屏幕上需要的東西。由於我不知道你在哪裏使用這段代碼,讓我們假設你有一個創建視圖來添加一個新的訂單。

爲您創建視圖中創建一個新的視圖模式:

public class OrderCreateViewModel 
{ 
    // Include other properties if needed, these are just for demo purposes 

    // This is the unique identifier of your order status, 
    // i.e. foreign key in your order table 
    public int OrderStatusId { get; set; } 
    // This is a list of all your order statuses populated from your order status table 
    public IEnumerable<OrderStatus> OrderStatuses { get; set; } 
} 

訂單狀態類:

public class OrderStatus 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

在您創建視圖,您將有以下:

@model MyProject.ViewModels.OrderCreateViewModel 

@using (Html.BeginForm()) 
{ 
    <table> 
      <tr> 
       <td><b>Order Status:</b></td> 
       <td> 
        @Html.DropDownListFor(x => x.OrderStatusId, 
         new SelectList(Model.OrderStatuses, "Id", "Name", Model.OrderStatusId), 
         "-- Select --" 
        ) 
        @Html.ValidationMessageFor(x => x.OrderStatusId) 
       </td> 
      </tr> 
    </table> 

    <!-- Add other HTML controls if required and your submit button --> 
} 

你創建操作方法:

public ActionResult Create() 
{ 
    OrderCreateViewModel viewModel = new OrderCreateViewModel 
    { 
      // Here you do database call to populate your dropdown 
      OrderStatuses = orderStatusService.GetAllOrderStatuses() 
    }; 

    return View(viewModel); 
} 

[HttpPost] 
public ActionResult Create(OrderCreateViewModel viewModel) 
{ 
    // Check that viewModel is not null 

    if (!ModelState.IsValid) 
    { 
      viewModel.OrderStatuses = orderStatusService.GetAllOrderStatuses(); 

      return View(viewModel); 
    } 

    // Mapping 

    // Insert order into database 

    // Return the view where you need to be 
} 

當您單擊提交按鈕並將其重定向回錯誤處理的創建視圖時,這將保持您的選擇。

我希望這會有所幫助。

1

確保您的返回選擇值是一個字符串,而不是在模型中聲明它時爲int。

實施例:

public class MyModel 
{ 
    public string StatusID { get; set; } 
}