How to make the DropDownListFor Don't repeat the Database data with the static list?

半城伤御伤魂 提交于 2019-12-12 03:52:45

问题


I have a DropDownListFor a static list of numbers of months if i select the first month 1 and make edit will find the DropDownListFor repeat the first month like this

DropDownListFor Code :

                    @Html.DropDownListFor(model=>model.FinancialInfo.FinancialExpiryMonth, (IEnumerable<SelectListItem>)ViewBag.FinancialMonths, (Model.FinancialInfo == null || Model.FinancialInfo.ExpiryDate == null) ? String.Empty : Model.FinancialInfo.ExpiryDate.Value.Month.ToString(), new { @class = "description-text" })

Note : the FinancialInfo.FinancialExpiryMonth is a Metadata element to make it as a View model.

Code of the ViewBag.FinancialMonths:

        ViewBag.FinancialMonths = ListOfNumbers(1, 12).Select(m => new SelectListItem { Text = m.ToString(), Value = m.ToString() });`

Code of the ListOfNumbers:

    public List<int> ListOfNumbers(int startNum, int endNum)
    {
        List<int> listOfNumbers = new List<int>();
        for (int i = startNum; i <= endNum; i++)
        {
            listOfNumbers.Add(i);
        }
        return listOfNumbers;
    }

回答1:


The first "1" that you see is a placeholder and it is generated by

(Model.FinancialInfo == null || Model.FinancialInfo.ExpiryDate == null) ? String.Empty : Model.FinancialInfo.ExpiryDate.Value.Month.ToString()

Replace the dropdown definition with:

@Html.DropDownListFor(model=>model.FinancialInfo.FinancialExpiryMonth, (IEnumerable<SelectListItem>)ViewBag.FinancialMonths, "Please select...", new { @class = "description-text" }) 

And you will see 'Please select...' as a placeholder

In order so pre-select a month simply assign a value to model.FinancialInfo.FinancialExpiryMonth




回答2:


Just By use the Lambda expresion in the Enumerable.Range and choose the selected condition is true when the Model have a value

                    @Html.DropDownListFor(model => model.FinancialInfo.FinancialExpiryMonth, Enumerable.Range(1, 12).Select(x => new SelectListItem
           {
               Value = x.ToString(),
               Text = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x),
               Selected = (Model.FinancialInfo == null || Model.FinancialInfo.ExpiryDate == null) ? false : true
           }), "Month", new { @class = "description-text" })


来源:https://stackoverflow.com/questions/40585332/how-to-make-the-dropdownlistfor-dont-repeat-the-database-data-with-the-static-l

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!