明确指定模型数据类型MVC / C#

时间:2016-04-15 10:42:34

标签: c# asp.net-mvc datetime

由于@Html.EditorFor()正在根据模型数据类型构建输入字段。我想使用此方法并为DATETIME类型的模型变量生成文本框,而不是日历。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以创建自己的帮助程序来显示和管理日期。

public static MvcHtmlString DatePickerFor<TModel, TProperty>
(this HtmlHelper<TModel> helper, 
Expression<Func<TModel, TProperty>> expression)
{
    string datePickerName = 
          ExpressionHelper.GetExpressionText(expression);
    string datePickerFullName = helper.ViewContext.ViewData.
                   TemplateInfo.GetFullHtmlFieldName
                   (datePickerName);
    string datePickerID = TagBuilder.CreateSanitizedId
                          (datePickerFullName);

    ModelMetadata metadata = ModelMetadata.FromLambdaExpression
                             (expression, helper.ViewData);
    DateTime datePickerValue = (metadata.Model == null ? 
                             DateTime.Now : DateTime.Parse(
                             metadata.Model.ToString()));

    TagBuilder tag = new TagBuilder("input");
    tag.Attributes.Add("name", datePickerFullName);
    tag.Attributes.Add("id", datePickerID);
    tag.Attributes.Add("type", "date");
    tag.Attributes.Add("value", datePickerValue.
                                ToString("yyyy-MM-dd"));

    IDictionary<string, object> validationAttributes = helper.
    GetUnobtrusiveValidationAttributes
    (datePickerFullName, metadata);

    foreach (string key in validationAttributes.Keys)
    {
        tag.Attributes.Add(key, validationAttributes[key].ToString());
    }

    MvcHtmlString html=new MvcHtmlString(
               tag.ToString(TagRenderMode.SelfClosing));
    return html;
}

准备使用助手

public class EmployeeMetadata
{
    [Required]
    public DateTime BirthDate { get; set; }
}

[MetadataType(typeof(EmployeeMetadata))]
public partial class Employee
{
}

    public ActionResult Index()
    {
        NorthwindEntities db = new NorthwindEntities();
        return View(db.Employees.First());
    }

你可以使用你的助手

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
@using(Html.BeginForm("ProcessForm","Home",FormMethod.Post))
    {        
        @Html.DatePicker("birthdateUnbound")
        @Html.DatePickerFor(m=>m.BirthDate)
        @Html.ValidationMessageFor(m=>m.BirthDate)
        <input type="submit" value="Submit" />
    }

提交表单

public ActionResult ProcessForm(Employee obj)
{
    return View("Index",obj);
}