3

For a while now I have tried to work my head around this small issue. Research done only confused me more and some attempts did not work.

So, if you think you can help me ease my pain, I will appreciate it greatly!

I'm new to ASP.NET MVC4 Mobile applications, I am creating a simple registration page with only a few details, one of them is Date of Birth, which I would prefer to be a set of dropdownlist instead of datepicker (as it is for mobiles I want it to be simple :) ).

Here is the bit of code that populates my dropdownlists in my View page:

<fieldset data-role="controlgroup" data-type="horizontal">
        <legend>D.O.B</legend>
            @Html.DropDownList("Day", Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString()}), "Day")
            @Html.DropDownList("Month", Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i)}), "Month")
            @Html.DropDownList("Year", Enumerable.Range(1900, 114).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString()}), "Year")
</fieldset>

I wanna be able to "map" the values from here to my Register model which right now it looks like this:

[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }

Any help or straight answer will be greatly appreciate it. If you need more info please feel free to ask. Thank you very much.

Regards

4

1 回答 1

10

您可以使用三个整数代替模型中的 DateTime

        public int Day { get; set; }
        public int Month { get; set; }
        public int Year { get; set; }

在你看来你会做

        @Html.DropDownListFor( model => model.Day, Enumerable.Range(1, 31).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString()}), "Day")
        @Html.DropDownListFor( model => model.Month, Enumerable.Range(1, 12).Select(i => new SelectListItem { Value = i.ToString(), Text = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i)}), "Month")
        @Html.DropDownListFor( model => model.Year,  Enumerable.Range(1900, 114).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString()}), "Year")

进入控制器后,您可以从这 3 个整数中创建一个日期时间并将它们存储在数据库中

DateTime date1 = new DateTime(year, month, day);

如果您需要有关 MVC 的表单和模型的更多指导,我建议您阅读此 ASP.NET MVC 指南 - 它非常全面:

http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-helpers,-forms-and-validation

于 2013-08-02T19:38:06.723 回答