2014-07-17 35 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 ...这个原因。现在就试试吧 –