0

我是唯一一个有这个问题的人,还是我的方向完全错误。

我有一个传递 DateTime 值的视图:

<div class="control-group">
@Html.Label("Appointment date", null, new { @class = "control-label" })
<div class="controls">
    <div class="input-append">
        @Html.TextBoxFor(model => model.Appointment.Client_PreferredDate, new { @readonly = "readonly" })
        <span class="add-on margin-fix"><i class="icon-th"></i></span>
    </div>
    <p class="help-block">
        @Html.ValidationMessageFor(model => model.Appointment.Client_PreferredDate)
    </p>
</div>

这些值被传递到 Controller 操作中(我可以看到该值,并且我知道它给出的格式不是 DateTime,即它将采用 dd-MM-yyyy 格式)。然后在控制器中我将重新格式化它。

[HttpPost]
public ActionResult RequestAppointment(General_Enquiry model, FormCollection fc)

{       
    model.Appointment.Client_PreferredDate = Utilities.formatDate(fc["Appointment.Client_PreferredDate"]);
    ModelState.Remove("Appointment.Client_PreferredDate");

try
{
    if (ModelState.IsValid)
    {
        model.Branch_Id = Convert.ToInt32(fc["selectedBranch"]);
        model.Appointment.Branch_Id = Convert.ToInt32(fc["selectedBranch"]);
        db.General_Enquiry.AddObject(model);
        db.SaveChanges();
        return RedirectToAction("AppointmentSuccess", "Client");
    }
}
catch (Exception e)
{
    Debug.WriteLine("{0} First exception caught.", e);
    Debug.WriteLine(e.InnerException);
    ModelState.AddModelError("", e);
}

return View(model);

}

我能做的最好的就是使用 ModelState.Remove(),我对此感到非常不舒服。我怀疑当我的模型从视图传递到控制器时,模型状态已经设置为无效,然后我才能在控制器中执行任何操作。有任何想法吗?

如果我调用 ModelState.Remove() 一切顺利,则 SQL 服务器数据库接受 DateTime。

如果至少我可以随时更新或“刷新”ModelState,它将解决我的问题。

干杯。

4

1 回答 1

4

我建议您对 DateTime 格式使用视图模型和自定义模型绑定器。

我们首先定义这个视图模型:

public class MyViewModel
{
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime PreferredDate { get; set; }
}

然后是控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            PreferredDate = DateTime.Now.AddDays(2)
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // model.PreferredDate will be correctly bound here so
        // that you don't need to twiddle with any FormCollection and 
        // removing stuff from ModelState, etc...
        return View(model);
    }
}

一个看法:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.PreferredDate)
    @Html.EditorFor(x => x.PreferredDate)
    @Html.ValidationMessageFor(x => x.PreferredDate)
    <button type="submit">OK</button>
}

最后是使用指定格式的自定义模型绑定器:

public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName,
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

将在以下位置注册Application_Start

ModelBinders.Binders.Add(typeof(DateTime), new MyDateTimeModelBinder());
于 2012-08-19T06:48:52.243 回答