-1

我编写自定义 ModelBinder,这是我的代码

    using System;
using System.Web.Mvc;

namespace GetOrganized.Code
{
    public class DateModelBinder : IModelBinder
    {
        #region IModelBinder Members

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentException("bindingContext");
            }
            DateTime theDate = default(DateTime);

            var day = FormPostedData<int>(bindingContext, "day");
            var month = FormPostedData<int>(bindingContext, "month");
            var year = FormPostedData<int>(bindingContext, "year");

            return CreateDateOrDefault(year, month, day, theDate);
        }

        #endregion

        private static T FormPostedData<T>(ModelBindingContext context, string id)
        {
            if (string.IsNullOrEmpty(id))
                return default(T);
            string key = string.Format("{0}.{1}", context.ModelName, id);
            ValueProviderResult result = context.ValueProvider.GetValue(key);
            if (result == null && context.FallbackToEmptyPrefix)
            {
                result = context.ValueProvider.GetValue(id);
                if (result == null)
                {
                    return default(T);
                }
            }
            context.ModelState.SetModelValue(id, result);
            T valueToReturn = default(T);
            try
            {
                if (result != null) valueToReturn = (T) result.ConvertTo(typeof (T));
            }
            catch
            {
            }
            return valueToReturn;
        }

        private DateTime CreateDateOrDefault(Int32 year, Int32 month, Int32 day, DateTime? defaultDate)
        {
            DateTime theDate = defaultDate ?? default(DateTime);
            try
            {
                theDate = new DateTime(year, month, day);
            }
            catch
            {
            }
            return theDate;
        }
    }
}

这是我的模特

    using System;
using System.Collections.Generic;
using System.Web.Mvc;
using GetOrganized.Code;

namespace GetOrganized.Models
{
    [ModelBinder(typeof (DateModelBinder))] 
    public class Todo
    {
        public bool Completed { get; set; }
        public string Title { get; set; }
        public Topic Topic { get; set; }
        public string Outcome { get; set; }
        public DateTime Date { get; set; }

        public DateTime DefualtDate
        {
            get { return DateTime.Now; }
        }

        public TimeSpan DifferenceDate { get; set; }
    }
}

但我得到错误

参数字典包含“GetOrganized.Controllers.TodoController”中方法“System.Web.Mvc.ActionResult Create(GetOrganized.Models.Todo)”的参数“todo”的无效条目。字典包含“System.DateTime”类型的值,但参数需要“GetOrganized.Models.Todo”类型的值。参数名称:参数请帮帮我

4

1 回答 1

0

您的自定义模型绑定器返回DateTime对象而不是Todo实例。

于 2012-09-23T20:36:12.573 回答