如何在@ Html.DropDownListFor中使选定的值成为以下代码? [英] How to make the selected value in @Html.DropDownListFor as following code?

查看:60
本文介绍了如何在@ Html.DropDownListFor中使选定的值成为以下代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在我的ASP网站中的日期下拉列表下填充1-31的下拉列表.

the following code populates the dropdown list for 1-31 under the date dropdown in my asp web.

@Html.DropDownListFor(
    model => model.eDate,
    Enumerable.Range(1, 31).Select(i => new SelectListItem 
        { Value = i.ToString(), Text = i.ToString() }))

现在,我正努力在该下拉菜单中预先选择一个值(例如,我希望当前日期为选定值).我假设今天是3,然后我添加了代码以检查它是否为3,并相应地设置了Selected属性的值...这是行不通的-在< option> 中没有selected属性当我在浏览器中查看源代码时.

Now I am struggling to have a value in that dropdown preselected (e.g. i want the current date is an selected value). I assume today is 3 and then I have added the code to check if it is 3 and set the value of the Selected property accordingly... It does not work - no selected attribute in <option> when I view the source in browser.

@Html.DropDownListFor(
    model => model.eDate, 
    Enumerable.Range(1, 31).Select(i => new SelectListItem 
        { Value = i.ToString(), Text = i.ToString(), Selected = i == 3 }))

请高手指教我吗?

推荐答案

尝试一下,它对我有用
控制器:

Try this, it work for me
Controller:

public ActionResult Index()
{
    var mymodel = new MyModel() { 
        eDate = DateTime.Now.Day
    };
    return View(mymodel);
}

查看:

@Html.DropDownListFor(
model => model.eDate,
Enumerable.Range(1, 31).Select(i => new SelectListItem 
    { Value = i.ToString(), Text = i.ToString() }))

这篇关于如何在@ Html.DropDownListFor中使选定的值成为以下代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆