asp.net MVC 3的SelectList与小数类型小数、类型、net、asp

2023-09-04 22:42:00 作者:荒凉如歌

我有,我是想在一个下拉,选择的值是行不通的,包括一个十进制值。我搞砸周围的$ C $下,没有运气了一段时间。最后,我用完全相同的code,但改变了一切从十进制int和它的作品。

I have a decimal value that I was trying to include in a drop down and the selected value was not working. I messed around with the code for a while with no luck. Eventually I used the exact same code but changed everything from decimal to int and it works.

在(InitialRewardPercent是一个十进制):

Before (InitialRewardPercent is a decimal):

@ Html.DropDownListFor(X => x.InitialRewardPercent,   CommonServices.GetRewardTermInitialPercents(Model.InitialRewardPercent))

@Html.DropDownListFor(x => x.InitialRewardPercent, CommonServices.GetRewardTermInitialPercents(Model.InitialRewardPercent))

CommonServices.GetRewardTermInitialPercents返回一个选择列表,并选择我传递值:

CommonServices.GetRewardTermInitialPercents returns a select list and selects the value I pass in:

返回新的SelectList(rewardTermInitialPercents,百分比,   PercentDisplay,selectedPercent);

return new SelectList(rewardTermInitialPercents, "Percent", "PercentDisplay", selectedPercent);

在(InitialRewardPercent是一个int):

After (InitialRewardPercent is an int):

@ Html.DropDownListFor(X => x.InitialRewardPercent,   CommonServices.GetRewardTermInitialPercents(Model.InitialRewardPercent   * 100))

ASP.NET MVC PagedList 教程

@Html.DropDownListFor(x => x.InitialRewardPercent, CommonServices.GetRewardTermInitialPercents(Model.InitialRewardPercent * 100))

我没有* 100,因为我想从0.25去到25基本上所有我所做的就是切换变量的类型从十进制int和作为选择的选择列表现在可以正确标识正确的行。

I did * 100 because I wanted to go from 0.25 to 25. Basically all I did was switch the variable type from decimal to int and the SelectList is now properly marking the correct row as selected.

可别人获得的SelectList与十进制值的工作还是我做错了什么?

Can anyone else get the SelectList to work with a decimal value or am I doing something wrong?

谢谢!

推荐答案

对我来说,以下工作:

型号:

public class MyViewModel
{
    public decimal InitialRewardPercent { get; set; }
    public IEnumerable<SelectListItem> Percents { get; set; }
}

控制器:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        InitialRewardPercent = 0.25m,
        Percents = new[]
        {
            new SelectListItem { Value = "0.15", Text = "15%" },
            new SelectListItem { Value = "0.25", Text = "25%" },
            new SelectListItem { Value = "0.35", Text = "35%" },
        }
    };
    return View(model);
}

查看:

@model MyViewModel
@Html.DropDownListFor(x => x.InitialRewardPercent, Model.Percents)

正如预期的那样,第二个项目是pselected在下拉$ P $视图显示时。所以,我在你的榜样猜某种程度上存在这样所以第一个是始终一致的 InitialRewardPercent 值的列表中没有任何价值preselected。

As expected, the second item is preselected in the dropdown when the view is shown. So I guess somehow in your example there is no value in the list that matches the value of InitialRewardPercent so the first is always preselected.