asp.net mvc 开发模式虽好,但是总感觉微软对视图view层面的支持不到位,例如连个像样的日期js控件都没有,无奈只能自己找资料研究扩展HtmlHelper来实现。本篇文章使用My97DatePicker日期控件来实现。
My97DatePicker 的下载地址:点击打开链接
打开vs 点击创建asp.net mvc 网站创建一个DataPicker的网站项目,不选择单元测试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
namespace DataPicker.Models
{
public class User
{
[DisplayName("姓名")]
public string Name { get; set; }
[DisplayName("年龄")]
public UInt16 Age { get; set; }
[DisplayName("生日")]
public DateTime Birthday { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Linq.Expressions;
namespace System.Web.Mvc
{
///
/// HtmlHelper for My97DatePicker
///
public static class My97DatePicker
{
private static string defaultFormat = "yyyy-MM-dd";
///
/// 使用特定的名称生成控件
///
/// HtmlHelper对象
/// 控件名称
/// Html文本
public static string Calendar(this HtmlHelper helper, string name)
{
return Calendar(helper, name, defaultFormat);
}
///
/// 使用特定的名称生成控件
///
/// HtmlHelper对象
/// 控件名称
/// 显示格式
/// Html文本
public static string Calendar(this HtmlHelper helper, string name, string format)
{
return GenerateHtml(name, null, format);
}
///
/// 使用特定的名称和初始值生成控件
///
/// HtmlHelper对象
/// 控件名称
/// 要显示的日期时间
/// Html文本
public static string Calendar(this HtmlHelper helper, string name, DateTime date)
{
return Calendar(helper, name, date, defaultFormat);
}
///
/// 使用特定的名称和初始值生成控件
///
/// HtmlHelper对象
/// 控件名称
/// 要显示的日期时间
/// 显示格式
/// Html文本
public static string Calendar(this HtmlHelper helper, string name, DateTime date, string format)
{
return GenerateHtml(name, date, format);
}
///
/// 通过lambda表达式生成控件
///
/// HtmlHelper对象
/// lambda表达式,指定要显示的属性及其所属对象
/// Html文本
public static string CalendarFor(this HtmlHelper helper, Expression> expression)
{
return CalendarFor(helper, expression, defaultFormat);
}
///
/// 通过lambda表达式生成控件
///
/// HtmlHelper对象
/// lambda表达式,指定要显示的属性及其所属对象
/// 显示格式
/// Html文本
public static string CalendarFor(this HtmlHelper helper, Expression> expression, string format)
{
string name = ExpressionHelper.GetExpressionText(expression);
DateTime value;
object data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
if (data != null && DateTime.TryParse(data.ToString(), out value))
{
return GenerateHtml(name, value, format);
}
else
{
return GenerateHtml(name, null, format);
}
}
///
/// 通过lambda表达式获取要显示的日期时间
///
/// HtmlHelper对象
/// lambda表达式,指定要显示的属性及其所属对象
/// 显示格式
/// Html文本
public static string CalendarDisplayFor(this HtmlHelper helper, Expression> expression, string format)
{
string name = ExpressionHelper.GetExpressionText(expression);
DateTime value;
object data = ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
if (data != null && DateTime.TryParse(data.ToString(), out value))
{
return value.ToString(format);
}
else
{
return string.Empty;
}
}
///
/// 通过lambda表达式获取要显示的日期时间
///
/// HtmlHelper对象
/// lambda表达式,指定要显示的属性及其所属对象
/// Html文本
public static string CalendarDisplayFor(this HtmlHelper helper, Expression> expression)
{
return CalendarDisplayFor(helper, expression, defaultFormat);
}
///
/// 生成输入框的Html
///
/// calendar的名称
/// calendar的值
/// html文本
private static string GenerateHtml(string name, DateTime? date, string format)
{
if (date != null)
{
return "";
}
else
{
return "";
}
}
}
}
如果需要使用日期控件其它样式或功能,请参考http://www.my97.net/dp/demo/index.htm功能与实例扩展以上代码中的GenerateHtml方法和CalendarDisplayFor方法。
生成User的控制器UserController
public class UserController : Controller
{
//
// GET: /User/
public ActionResult Index()
{
return View();
}
//
// GET: /User/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /User/Create
public ActionResult Create()
{
return View();
}
//
// POST: /User/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /User/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /User/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /User/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /User/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
再生成User的Create页面,选择强类型User,如果没有类型,请重新生成一下项目。
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
Create
Create
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<% } %>
<%= Html.ActionLink("Back to List", "Index") %>
将其中生日日期的相关html代码修改一下,即
<%= Html.LabelFor(model => model.Birthday) %>
<%= Html.TextBoxFor(model => model.Birthday) %>
<%= Html.ValidationMessageFor(model => model.Birthday) %>
修改为:
<%: Html.LabelFor(model => model.Birthday)%>
<%= Html.CalendarFor(model => model.Birthday)%>
<%: Html.ValidationMessageFor(model => model.Birthday)%>
routes.MapRoute(
"Default", // 路由名称
"{controller}/{action}/{id}", // 带有参数的 URL
new { controller = "User", action = "Create", id = UrlParameter.Optional } // 参数默认值
);