2014-07-17 39 views
0

沒有發現這件事。如何使用模型選擇選項?

我有一個模型:

public class Filter 
{ 
    public string No { get; set; } 

    public DateTime EndTime { get; set; } 

    public string FilterStatus { get; set; } 
} 

在我看來,我有第二件事:

<select id="status" name="status" style="width: 120px;font-size: 0.9em; padding: 0;" class="k-dropdown"> 
    <option>-- Select --</option> 
    <option>Yes</option> 
    <option>No</option> 
</select> 

我試圖做的事情是選擇的選項,這與Model.FilterStatus等於。例如,如果狀態爲'是',則下拉框中的文本應爲'是'。但有沒有辦法做到這一點?用JavaScript或不?

+0

爲什麼不使用'@ Html.DropdownFor()'使其正確綁定? –

+0

另外我在我的控制器中使用FormCollection。我想我不能從那裏下拉數據。 (而且我也是mvc的新手)。 –

+1

編輯你的問題,並把完整的代碼,所以我們可以瞭解情況,即''Controller'類與'Action'方法代碼(MVC部分),因爲IMO'FormCollection'只用於其http' POST'及其在'Action'方法中使用 –

回答

1

您可以使用Html.DropDown助手。此幫助程序通過顯示的選項獲取IEnumerable。 在您的控制器中,您可以在ViewBag中發送下拉列表的值或使用View Model。您的視圖模型的這一特性必須與SelectListItem(S)的列表,包括您的兩個選項是和否,然後用你的過濾器的值來選擇這樣的正確的選擇:

ViewBag.Status = new List<SelectListItem>(){ 
    new SelectListItem 
    { 
     Value = "Yes", 
     Text = "Yes", 
     Selected = yourFilter.FilterStatus //If your status is Yes this will be true 
              //otherwise false. 
    }, 
    new SelectListItem 
    { 
     Value = "No", 
     Text = "No", 
     Selected = yourFilter.FilterStatus //If your status is No this will be true 
              //otherwise false. 
    } 
}; 

然後在您的視圖您可以打印使用HTML幫助您的下拉列表:

@Html.DropDownList("Status", "--Select--") 

使用ViewBag講究的是屬性的名稱有名字的助手匹配,這將是相同的名稱,該表單將寄在提交表單時回到控制器。

如果您使用的視圖模型版本,那我建議你測試的目的,你必須創建一個視圖模型,並指定下拉值是財產,是這樣的:

//Don't create this class on the controller! This is only as an example. 
public class FilterViewModel { 
    public bool Status {get; set;} 
    public IEnumerable<SelectListItem> statusDropDown {get; set;} 
} 

var myViewModel = new FilterViewModel(); 
myViewModel.statusDropDown = new List<SelectListItem>(){ 
    new SelectListItem 
    { 
     Value = "Yes", 
     Text = "Yes", 
     Selected = yourFilter.FilterStatus 
    }, 
    new SelectListItem 
    { 
     Value = "No", 
     Text = "No", 
     Selected = yourFilter.FilterStatus 
    } 
}; 

return View(myViewModel); 

你可以使用您的視圖中的以下幫助程序:

@model Controllers.YourController.FilterViewModel 
@Html.DropDownListFor(model => model.Status, Model.statusDropDown, "--Select--") 
+0

添加了一些更改,但此示例工作得很好,謝謝。 –

0
@model Filter 

@Html.DropDownListFor(model => model.FilterStatus, new SelectList(
    new List<SelectListItem> { 
     new SelectListItem { Text = "Yes", Value = "Yes" }, 
     new SelectListItem { Text = "No", Value = "No" } 
    }, "Value", "Text"), 
    "--- Select Option ---", new { @class = "k-dropdown" }) 
+0

謝謝你這麼快的回答,但我還有一個。也許聽起來很愚蠢,但是,它會如何工作?我的意思是,現在從我的下拉列表中選擇了FormCollection。正如我所看到的,這個版本不能像那樣使用。 –

+0

當然它可以,但爲什麼使用FormCollection而不是你的模型,所以它已經綁定(例如'[HttpPost](public ActionResult YourAction(Filter model){...') –

+0

它可以?如何?例如,現在我使用收集[「狀態」]來獲得選定的選項,但需要id,或者我可以做類似於新的{@class =「k-dropdown」,@ Id =「status」}?HttpPost ...這個原因。現在就試試吧 –