似乎无法从表单中保存枚举值

时间:2014-04-10 13:46:53

标签: razor drop-down-menu

我无法找到导致错误的原因。我从枚举到下拉列表中获取值,但我不知道这是否是问题,因为异常只发生在浏览器中,而不是在VS中。

查看:

@model HiltiHaninge.Models.CellModel
@using HiltiHaninge.Models
@{
var db = new HiltiHaninge.Models.HiltiHaningeContext();
var users = db.UserProfiles.ToList();
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("CreateCell", "Schema", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>Ny träning</legend>

    <div class="editor-label">
        <p>Tid från:</p>
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(m => m.TimeFromHour, htmlAttributes: new { @class = "main_content_fieldset_text" })
        @Html.ValidationMessageFor(m => m.TimeFromHour)
        @Html.TextBoxFor(m => m.TimeFromMinute, htmlAttributes: new { @class = "main_content_fieldset_text" })
        @Html.ValidationMessageFor(m => m.TimeFromMinute)
    </div>

    <div class="editor-label">
        <p>Tid till:</p>
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(m => m.TimeToHour, htmlAttributes: new { @class = "main_content_fieldset_text" })
        @Html.ValidationMessageFor(m => m.TimeToHour)
        @Html.TextBoxFor(m => m.TimeToMinute, htmlAttributes: new { @class = "main_content_fieldset_text" })
        @Html.ValidationMessageFor(m => m.TimeToMinute)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Discipline, htmlAttributes: new { @class = "main_content_fieldset_text" })
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(m => m.Discipline, Enum.GetValues(typeof(Discplines)).Cast<Discplines>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))
        @Html.ValidationMessageFor(m => m.Discipline)
    </div>

    <div class="editor-label">
        @Html.LabelFor(m => m.Level, htmlAttributes: new { @class = "main_content_fieldset_text" })
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(m => m.Level, Enum.GetValues(typeof(Levels)).Cast<Levels>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))
        @Html.ValidationMessageFor(m => m.Level)
    </div>

    <div class="editor-label">
        @Html.LabelFor(m => m.Coach, htmlAttributes: new { @class = "main_tcontent_fieldset_text" })
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(m => m.Coach, new SelectList(users, "UserName", "UserName"))
        @Html.ValidationMessageFor(m => m.Coach)
    </div>

    <input type="submit" value="Skapa" />
</fieldset>
}

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
 }

和控制器:

 public ActionResult CreateCell()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateCell(CellModel cell, Days day)
    {
        if (ModelState.IsValid)
        {
            using (var db = new HiltiHaningeContext())
            {
                var schedule = new DaySchedule();
                var c = new CellEntity
                    {
                        TimeFromHour = cell.TimeFromHour,
                        TimeFromMinute = cell.TimeFromMinute,
                        TimeToHour = cell.TimeToHour,
                        TimeToMinute = cell.TimeToMinute,
                        Discipline = cell.Discipline,
                        Coach = cell.Coach
                    };
                schedule.Bookings.Add(c);
                //schedule.Day = day;

                db.CellEntities.Add(c);
                db.DaySchedules.Add(schedule);
                db.SaveChanges();
                return RedirectToAction("Index", "Schema");
            }
        }
        else
        {
            ModelState.Clear();
        }
        return View(cell);
    }

点击“Skapa”后没有任何进一步的信息,并且到达断点,我崩溃了。

无法将'System.Int32'类型的对象强制转换为'System.String'。

请帮助,因为我真的被困在这里。

根据要求提供StackTrace:

[InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.]
System.ComponentModel.DataAnnotations.StringLengthAttribute.IsValid(Object value) +46
System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext) +115
System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext) +29
System.Web.Mvc.<Validate>d__15.MoveNext() +158
System.Web.Mvc.<Validate>d__1.MoveNext() +311
System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +135
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +66
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1315
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +416
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +381
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
  System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +49
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

最后模特:

 public class CellEntity
 {
    public virtual int TimeFromMinute { get; set; }
    public virtual int TimeFromHour { get; set; }
    public virtual int TimeToMinute { get; set; }
    public virtual int TimeToHour { get; set; }
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public virtual Days Day { get; set; }
    public virtual Discplines Discipline { get; set; }
    //public virtual UserProfile Coach { get; set; }
    public virtual string Coach { get; set; }
    public virtual Levels Level { get; set; }
}
public enum Levels
{
    Nybörjare,
    Avancerad,
    Barn
}
public enum Days
{
    Måndag,
    Tisdag,
    Onsdag,
    Torsdag,
    Fredag,
    Lördag,
    Söndag
}
public enum Discplines
{
    BJJ,
    Thai,
    SW,
    MMA,
    Mix
}
public class DaySchedule
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public virtual Days Day { get; set; }
    public virtual List<CellEntity> Bookings { get; set; }
}
public class CellModel 
{
    [Required(ErrorMessage = "Måste fylla i från vilken timme.")]
    //[StringLength(2, ErrorMessage = "Måste vara ett giltigt tvåsiffrigt klockslag.", MinimumLength = 2)]
    [RegularExpression(@"^[0-9]*$", ErrorMessage = "Endast siffror tillåtna.")]
    [Display(Name = "Timme från")]
    public int TimeFromHour { get; set; }

    [Required(ErrorMessage = "Måste fylla i från vilka minuter.")]
    //[StringLength(2, ErrorMessage = "Måste vara ett giltigt tvåsiffrigt klockslag.", MinimumLength = 2)]
    [RegularExpression(@"^[0-9]*$", ErrorMessage = "Endast siffror tillåtna.")]
    [Display(Name = "Minut från")]
    public int TimeFromMinute { get; set; }

    [Required(ErrorMessage = "Måste fylla i till vilken timme.")]
    //[StringLength(2, ErrorMessage = "Måste vara ett giltigt tvåsiffrigt klockslag.", MinimumLength = 2)]
    [RegularExpression(@"^[0-9]*$", ErrorMessage = "Endast siffror tillåtna.")]
    [Display(Name = "Timme till")]
    public int TimeToHour { get; set; }

    [Required(ErrorMessage = "Måste fylla i till vilka minuter.")]
    //[StringLength(2, ErrorMessage = "Måste vara ett giltigt tvåsiffrigt klockslag.", MinimumLength = 2)]
    [RegularExpression(@"^[0-9]*$", ErrorMessage = "Endast siffror tillåtna.")]
    [Display(Name = "Minut till")]
    public int TimeToMinute { get; set; }

    [Required(ErrorMessage = "Måste fylla i vilken disciplin det gäller (stil).")]
    [Display(Name = "Disciplin")]
    public Discplines Discipline { get; set; }

    [Required(ErrorMessage = "Måste välja en tränare till passet.")]
    [Display(Name = "Tränare")]
    public string Coach { get; set; }

    [Required(ErrorMessage = "Måste välja en nivå på passet.")]
    [Display(Name = "Nivå")]
    public Levels Level { get; set; }
 }

0 个答案:

没有答案