2014-01-08 13 views
0

我目前正在向MVC4中的Controller發佈List<MyModel>如何在MVC中正確設置下拉列表選定的值

我可以正確更新我發佈的所有模型,但是當頁面加載時,我無法在下拉列表中選擇正確的值。

這工作正常,如果我使用文本框,但dropdownlist將不會選擇正確的值。該頁面在頁面加載時正確填充。

我在視圖中使用作爲循環,因此我可以將我的列表發佈到控制器。

該文本框的ID是[0] .PurgeSeconds。當我用具有相同ID的下拉列表替換它時,它不起作用。

如何將下拉列表設置爲正確的選定值?

型號

namespace MyMvc.Models 
{ 
    [Table("MyTable")] 
    public class DataRetentionConfig 
    { 
     [Key] 
     [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public int PurgeSeconds { get; set; } 
    } 
} 

控制器

[HttpPost] 
public ActionResult Save(ICollection<DataRetentionConfig> models) 
{ 
    foreach (var model in models) 
    { 
     using (var db = new FoySqlContext()) 
     { 
      var retentionRecord = db.DataRetentionConfigs.Find(model.Id); 
      retentionRecord.PurgeTime = model.PurgeTime; 
      db.SaveChanges(); 
     } 
    } 

    return RedirectToAction("Index"); 
} 

查看

@model List<MyMvc.Models.DataRetentionConfig> 
@{ 
    ViewBag.Title = "Index"; 
} 
@using (Html.BeginForm("Save", "Retention", FormMethod.Post)) 
{ 
    <table class="table table-striped"> 
     <thead> 
      <tr> 
       <th>Name</th> 
       <th>Purge Seconds</th> 
      </tr> 
     </thead> 
     <tbody> 
      @for (var i = 0; i < Model.Count; i++) 
      { 
       if (Model[i].DataType == 1) 
       { 
        <tr> 
         <td> 
          @Html.HiddenFor(m => m[i].Id) 
          @Model[i].Name 
         </td> 
         <td> 
          @*@Html.TextBoxFor(m => m[i].PurgeSeconds)*@ 
          @Html.DropDownListFor(m => m.[i].PurgeSeconds, new MyMvc.Models.Configuration.DataRetentionConfig().PurgeTimeOptions(), new { @name = Model[i].PurgeTime, @class = "form-control", @style = "width: 150px;" }) 
         </td> 
        </tr> 
       } 
      } 
     </tbody> 
    </table> 
    <p> 
     <input type="submit" value="Save" class="btn btn-large btn-primary" /> 
     @*<button type="reset" class="btn">Cancel</button>*@ 
     <a class="btn" href="@Url.Action("Index", "Retention")">Cancel</a> 
    </p> 
} 
+0

新的MyMvc.Models.Configuration.DataRetentionConfig()。PurgeTimeOptions()包含什麼?它是一個SelectList嗎? – sunshineDev

回答

2

嘗試

@Html.DropDownListFor(m => m.[i].PurgeSeconds, new SelectList(YOUR_LIST, "PurgeSeconds", "Name", m.[i].PurgeSeconds), new { @name = Model[i].PurgeTime, @class = "form-control", @style = "width: 150px;" }) 

YOUR_LIST是的列表中,您有一個項目在下拉列表中顯示(可能MyMvc.Models.Configuration.DataRetentionConfig()。PurgeTimeOptions(),我不知道)。 最好使用ViewModel,您可以在其中存儲YOUR_LIST和其他數據以進行顯示和編輯。

相關問題