模型绑定下拉列表选择的值 [英] Model binding dropdown selected value
本文介绍了模型绑定下拉列表选择的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型,该模型有一个公开名单<串GT;小时{搞定;组; }
和构造函数
I have a model and that model has a public List<string> Hour { get; set; }
and the constructor
public SendToList()
{
Hour = new List<string> { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" };
}
我的问题是,为什么我没有拿到这个所选值
My question is why don't I get a selected value for this
@Html.DropDownListFor(model => model.Hour, Model.Hour.Select(
x => new SelectListItem
{
Text = x,
Value = x,
Selected = DateTime.Now.Hour == Convert.ToInt32(x)
}
))
不过,我在这里得到一个选择的值。
But I get a selected value here.
@Html.DropDownList("Model.Hour", Model.Hour.Select(
x => new SelectListItem
{
Text = x,
Value = x,
Selected = DateTime.Now.Hour == Convert.ToInt32(x)
}
))
有什么区别?
推荐答案
由于你需要选择的值赋给模型。
Because you need to assign the selected value to your model.
因此,我建议你采取下列措施。让我们先从视图模型:
So I would recommend you the following approach. Let's start with the view model:
public class MyViewModel
{
// this will hold the selected value
public string Hour { get; set; }
public IEnumerable<SelectListItem> Hours
{
get
{
return Enumerable
.Range(0, 23)
.Select(x => new SelectListItem {
Value = x.ToString("00"),
Text = x.ToString("00")
});
}
}
}
您可以填充此视图控制器内部模型:
you could populate this view model inside the controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// Set the Hour property to the desired value
// you would like to bind to
Hour = DateTime.Now.Hour.ToString("00")
};
return View(model);
}
}
和在你看来简单:
@Html.DropDownListFor(
x => x.Hour,
new SelectList(Model.Hours, "Value", "Text")
)
这篇关于模型绑定下拉列表选择的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文