2012-01-18 18 views
0

選択した値が変更されたときにページをリロードするドロップダウンリストがあります。これは正常に動作し、レンダリングされます。唯一の問題は、ドロップダウンリストがデフォルト値に戻ることです。 ViewBag.Valueと一致するようにデフォルト値を変更するにはどうすればよいですか?デフォルトのドロップダウンデフュルト値をビューバックに基づいて設定します

@Html.DropDownListFor(model => model.LevelId, 
          (
           from choice in 
            (from p in Model.Defaults 
            group p by new { p.LevelId, p.LevelDescription } into c 
            select new { c.Key.LevelId, c.Key.LevelDescription }) 
           select new SelectListItem 
              { 
               Text = choice.LevelDescription, 
               Value = choice.LevelId.ToString(), 
               Selected = false 
              })) 

JScriptのあなたのように初期化されますIEnumerable<SelectListItem>になりますあなたはあなたのビューモデルにプロパティを追加することができ

答えて

1

に渡されたのparamに基づいてコントローラがViewBag.Levelを設定

$("#LevelId").change(function() { 

     var clientId = @Model.ClientId; 
     var compareDate = $("#EffectiveDate").val(); 
     var level = $(this).val(); 
     var params = $.param({ clientId: clientId, compareDate: compareDate, level : level }); 
     var link = '@Url.Action("Create", "Choices")'; //"\\Choices\\RefreshView"; 
     var url = link + "?" + params; 
     document.location = url; 
    }); 

それはあなたのコントローラのものです。それからちょうどあなたが事前に選択したい値にLevelIdプロパティ設定:

public ActionResult Foo(string level) 
{ 
    var model = new MyViewModel(); 
    var values = from choice in 
     (from p in Model.Defaults 
     group p by new { p.LevelId, p.LevelDescription } into c 
     select new { c.Key.LevelId, c.Key.LevelDescription }) 
     select new { 
      Text = choice.LevelDescription, 
      Value = choice.LevelId.ToString() 
     } 
    ); 
    model.Items = new SelectList(values, "Text", "Value"); 
    model.LevelId = level; 
    return View(model); 
} 

をして、あなたのビューで:

@Html.DropDownListFor(model => model.LevelId, Model.Items) 
+0

私はmodel.items =新しいSelectListの(値のため、このエラーが発生します。.. ..)エラー 'System.Web.Mvc.SelectList'型を暗黙的に 'System.Collections.Generic.IEnumerable 'に変換できません。 –

+0

@atbyrdの場合は、IEnumerable の代わりに 'IEnumerable 'を使用してください。あなたは間違った 'SelectListItem'クラスを選んだようです:-) –

+0

yeaはそれを理解しました。あなたの助けてくれてありがとう! –

関連する問題