jqGrid对可空日期类型数据转换时的错误处理

用jqGrid展现数据库表,若数据库表存在日期类型,则在poco中要声明可空字段类型。如以下FillinDate 字段:

public class Project2Weekly

{
public int Id { get; set; }
public string Progress { get; set; }
public string Problem { get; set; }
public string NextPlan { get; set; }
public string Evidence { get; set; }
public DateTime? FillinDate { get; set; }
public string FillinMan { get; set; }
public int Pid { get; set; }
}

当用户在编辑完表数据保存时,一般要调用JqGrid.EditParams方法对Form上的数据进行转换,如:

public JsonResult EditWeekly()
{
NameValueCollection nvc = Request.Form;
Project2Weekly model = JqGrid.EditParams<Project2Weekly>(nvc);
manager.EditWeekly(model);
return Json(new { success = true });
}

实践发现,Form上日期类型总是保存不到数据库中。跟踪发现,poco中的DateTime?数据类型在 JqGrid.EditParams方法中没有被识别为DateTime类型,而是被识别为“Nullable`1”(System.Nullable`1[System.DateTime]),导致值被设置为null。以下为JqGrid.EditParams方法部分源代码:

public static T EditParams<T>(NameValueCollection nvc)

        {

            Type type = typeof(T);

            PropertyInfo[] pis = type.GetProperties();

 

            T t = (T)Activator.CreateInstance(type);

 

            foreach (PropertyInfo pi in pis)

            {

                string data = nvc[pi.Name] == null ? "" : nvc[pi.Name].ToString().Trim();

                dynamic value;

                switch (pi.PropertyType.Name)

                {

                    case "DateTime":

                        if (data == "")

                            value = DateTime.MinValue;

                        else

                        {

                            value = Convert.ToDateTime(data);

                            if (value == DateTime.MinValue)

                                value = DateTime.Now;

                        }

                        break;

                        .

                        .

                        .

                    case "String":

                        value = data;

                        break;

                    default:

                        value = null;

                        break;

                }

 

                pi.SetValue(t, value, null);

            }

 

            return t;

        }

    }

解决此问题的方法也很简单,在case "DateTime" 代码处增加一行来处理"Nullable`1"类型即可。代码修改如下:

                switch (pi.PropertyType.Name)

                {

                    case "DateTime":

                    case "Nullable`1":

 

                        if (data == "")

                            value = DateTime.MinValue;

                        else

                        {

                            value = Convert.ToDateTime(data);

                            if (value == DateTime.MinValue)

                                value = DateTime.Now;

                        }

                        break;

原文地址:https://www.cnblogs.com/jackkwok/p/3110491.html