【问题标题】:DateTime Selectlist from model to view to controller从模型到视图到控制器的日期时间选择列表
【发布时间】:2013-08-15 22:59:58
【问题描述】:

我正在努力使用 MVC 和 EF 制作我的第一款游戏。

我有一个名为 Race 的课程。 这有一个 DateTime 字段,它将保存比赛将由服务器“自动”进行的时间。

现在当用户创建这个种族时。他们必须在这里选择一个日期时间。 列表中显示的日期时间将添加到竞赛模型中。 我有一个根据今天和接下来的 2 天转换为日期的时间列表。

我遇到的问题是。 使用干净的方法。 (我的选择列表为空) 使用脏方法(我的模型无法保存,因为 DateTime 字段是字符串而不是 DateTime 字段)

/* 种族等级 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace DOCCL.Models
{
    public class Race
    {
        [Key]
        public int Id { get; set; }
        [Required(ErrorMessage = "Name is required")]
        public string Name { get; set; }
        [Required(ErrorMessage = "Purse is required")]
        public int Purse { get; set; }
        public int? Slots { get; set; }
        public int SlotPrice { get; set; }
        public DateTime? RaceTime { get; set; }

        public int? TrackId { get; set; }
        public virtual Track Track { get; set; }

        public int? OwnerId { get; set; }
        public virtual User Owner { get; set; }

        public virtual ICollection<Horse> RacingHorses { get; set; }

        public virtual ICollection<RaceResult> RaceResults { get; set; }

        public Race()
        {
            SlotPrice = 0; //default value
            Slots = 8;


        }

        public SelectList SlotOptions
        {
            get
            {
                return new SelectList(AllSlotOptions, "Index", "Slot", Slots);
            }
        }

        public static IEnumerable<SlotOption> AllSlotOptions
        {
            get
            {
                int[] slotOptions = { 8, 12, 16 };
                int index = 1;
                foreach (int slotOption in slotOptions)
                {
                    yield return new SlotOption
                    {
                        Index = index,
                        Slot = slotOption,
                    };
                    ++index;
                }
            }
        }

        public class SlotOption
        {
            public int Index { get; set; }
            public int Slot { get; set; }
        }

        public SelectList TimeSlotOptions
        {
            get
            {
                return new SelectList(AllTimeSlotOptions, "Index", "Slot", RaceTime);
            }
        }

        public static IEnumerable<TimeSlotOption> AllTimeSlotOptions
        {
            get
            {
                int[] slotOptions = { 9, 12, 15, 18, 21 };

                int index = 1;
                for (int day = 0; day <= 2; day++)
                {
                    foreach (int slotOption in slotOptions)
                    {
                        DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + day, slotOption, 0, 0);

                        if (dt > DateTime.Now)
                        {
                            yield return new TimeSlotOption
                            {
                                Index = index,
                                Slot = dt
                            };
                        }
                        ++index;
                    }
                }
            }
        }

        public class TimeSlotOption
        {
            public int Index { get; set; }
            public DateTime Slot { get; set; }
        }
    }
}

/* RaceController */

[Authorize]
    public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [Authorize]

    public ActionResult Create(Race race)
    {
        User user = entities.Users.SingleOrDefault(u => u.UserName.Equals(User.Identity.Name));
        if (ModelState.IsValid)
        {
            user.Finances -= 500;
            entities.Races.Add(race);
            entities.SaveChanges();

            return RedirectToAction("Index");
        }
        return View(race);
    }

/* 种族\创建 */

@model DOCCL.Models.Race

@{
    Layout = "~/Views/Shared/_frontend.cshtml";
    ViewBag.Title = "Create";
}


<div class="ten columns alpha omega">
    <h2>Create race</h2>
</div>

@using(Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend></legend>
            <div class="ten columns alpha omega">
                <div class="three columns alpha">@Html.LabelFor(race => race.Name)</div>
                <div class="three columns">@Html.TextBoxFor(race => race.Name)</div>
                <div class="four columns omega">@Html.ValidationMessageFor(race => race.Name)</div>
            </div>
            <div class="ten columns alpha omega">
                <div class="three columns alpha">@Html.LabelFor(race => race.RaceTime)</div>
                <div class="three columns">@Html.DropDownList("RaceTime", DOCCL.Models.Race.AllTimeSlotOptions.Select(ts => new SelectListItem {Value = ts.Slot.ToString(), Text = ts.Slot.ToString() }) , "-- Race --")</div>
                <div class="four columns omega">@Html.ValidationMessageFor(race => race.RaceTime)</div>
            </div>
            <div class="ten columns alpha omega">
                <div class="three columns alpha">@Html.LabelFor(race => race.Slots)</div>
                <div class="three columns">@Html.DropDownList("Slots", DOCCL.Models.Race.AllSlotOptions.Select(ts => new SelectListItem {Value = ts.Index.ToString(), Text = ts.Slot.ToString() }) , "-- Slots --")</div>
                <div class="four columns omega">@Html.ValidationMessageFor(race => race.Slots)</div>
            </div>
            <div class="ten columns alpha omega">
                <div class="three columns alpha">@Html.LabelFor(race => race.SlotPrice)</div>
                <div class="three columns">@Html.TextBoxFor(race => race.SlotPrice)</div>
                <div class="four columns omega">@Html.ValidationMessageFor(race => race.SlotPrice)</div>
            </div>
            <div class="ten columns alpha omega">
                <div class="offset-by-eight two columns alpha omega">
                    <input type="submit" class="button" value="Create" />
                </div>
            </div>
    </fieldset>
}

/* 清理尝试 */

<div class="ten columns alpha omega">
    <div class="three columns alpha">@Html.LabelFor(race => race.RaceTime)</div>
    <div class="three columns">@Html.DropDownListFor(model => model.RaceTime, Model.TimeSlotOptions, "-- Race time --")</div>
    <div class="four columns omega">@Html.ValidationMessageFor(race => race.RaceTime)</div>
</div>
<div class="ten columns alpha omega">
    <div class="three columns alpha">@Html.LabelFor(race => race.Slots)</div>
    <div class="three columns">@Html.DropDownListFor(model => model.Slots, Model.SlotOptions, "-- Slot --")</div>
    <div class="four columns omega">@Html.ValidationMessageFor(race => race.Slots)</div>
</div>

显然最后一个是最好的,它返回 null 因为我实际上还没有 Race 对象。因此我无法到达选择列表。

你们中有人知道如何正确地做到这一点吗?

【问题讨论】:

  • 仍在寻找对此的某种见解。如果有人有任何方法可以做到这一点,我会非常乐意在必要时重新考虑。希望在制作这款游戏​​的过程中学习。

标签: c# asp.net-mvc asp.net-mvc-3 entity-framework-4 code-first


【解决方案1】:

我会尝试这样的事情

@Html.DropDownListFor(x => x.RaceTime, new SelectList(Model.TimeSlotOptions, "Id", "Name"), "-- Race time --")

而不是

@Html.DropDownListFor(model => model.RaceTime, Model.TimeSlotOptions, "-- Race time --")

【讨论】:

  • 试一试。同样的问题。空引用异常。
【解决方案2】:

我最终将这 2 个列表移到了一个通用的辅助类中。 并从那里实例化它们。

成功了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2012-12-12
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多