2014-04-22 93 views
0

當頁面加載時,我的下拉菜單沒有填充正確的狀態。它總是從列表的開始處開始。現在,我只是通過使用ViewBag來傳遞列表,這可能是問題所在。DropDownListFor不填充正確的值

正如你可以在視圖代碼中看到的,我有一個使用我的Model.StateList的dropdownlist,但我似乎無法得到它的工作。

addy.State被格式化爲StateAbbr

和我的下拉菜單(使用(SelectList) ViewBag.StateList方法時,使此格式的信息列表(例如 「CT」, 「AL」, 「AK」。):

<option value="AL">Alabama</option> 
<option value="AR">Arkansas</option> 

模型

public class EditOrderViewModel 
    { 
     public List<State> StateList { get; set; } 
    } 

控制器

public ActionResult EditOrder(int orderId) 
{ 
var model = repositoryScheduling.Order_FindById(orderId); 

var stateList = GetStateList(); 
ViewBag.StateList = new SelectList(stateList, "StateAbbr", "StateNamne"); 

model.StateList = GetStateList(); 
return View(model); 
} 

查看

foreach(var addy in Model.Address) 
{ 
         <div class="form-group-CityState"> 
          <div class="input-group" style="border-right: 0px"> 
           <span class="input-group-addon CitySpanAddon" style="text-align: left; border-right: 0px">@Html.LabelFor(model => addy.City)</span> 
           // @*@Html.DropDownListFor(model => addy.State, Model.StateList, new {id = "SelectState", @class = "SelectState"})*@ 
           @Html.DropDownListFor(model => addy.State, (SelectList)ViewBag.StateList, new { id = "SelectState", @class = "SelectState" }) 
           @Html.ValidationMessageFor(model => addy.State) 
          </div> 
         </div> 
} 

不知道這是什麼會做,但在這裏你去

public List<State> GetStateListAll() 
     { 
      const string query = @"SELECT * 
         FROM 
          states;"; 


      return this.db.Query<State>(query).ToList(); 
     } 
+0

在DropDownFor的第一個參數是它保持選定值並將其發佈到服務器如果需要的對象,同樣PARAM將是下拉列表中選定的值。 所以如果你將你的控制器中的addy.State設置爲你選擇的項目,它應該可以工作。 – Aram

+0

向我們展示您的GetStateList方法。 – milagvoniduak

+0

OK @ MyP3uK,我添加了該功能,但不知道它是否會有所幫助 – MaylorTaylor

回答

0

您需要設置您創建的SelectList對象的SelectedValue值。

public ActionResult EditOrder(int orderId) {model} repositoryScheduling.Order_FindById(orderId);

var stateList = GetStateList(); 
var selectStateList = new SelectList(stateList, "StateAbbr", "StateNamne"); 
selecteStateList.SelectedValue = model.State // your state id... whatever is in your model. 
ViewBag.StateList = selectStateList; 
return View(model); 

}

0

這是我的回答。我不知道該SelectList()有一個變量selectedValue

int i = 0; 
    foreach (var addy in model.Address) 
    { 
     var countyList = GetCountyList(addy.State); 
     string CountyListCount = "CountyList" + i; 
     string StateListCount = "StateList" + i; 
     ViewData[CountyListCount] = new SelectList(countyList, null, "CountyName",addy.County); 
     ViewData[StateListCount] = new SelectList(stateList, "StateAbbr", "StateName", addy.State); 
     i++; 
    }