asp.net-mvc 使用 ASP.Net MVC 的 Html.TextBoxFor 时如何在强类型视图中格式化值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2088139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:04:14  来源:igfitidea点击:

How to format the value in a strongy typed view when using ASP.Net MVC's Html.TextBoxFor

asp.net-mvcformathtml-helper

提问by Paul Speranza

I am trying to format a date rendered by ASP.Net MVC's TextBoxFor using the value of a strongly typed view. The date is nullable so if it is null I want to see a blank value, otherwise I want to see it in the format MM/dd/yyyy.

我正在尝试使用强类型视图的值来格式化由 ASP.Net MVC 的 TextBoxFor 呈现的日期。日期可以为空,所以如果它为空,我想看到一个空白值,否则我想以 MM/dd/yyyy 格式查看它。

<%= Html.TextBoxFor(model => model.BirthDate, new { style = "width: 75px;" })%>

Thanks,
Paul Speranza

谢谢,
保罗·斯佩兰萨

回答by David Glenn

You can keep the strong typing by using a custom editor templateand Html.EditorFor()instead of Html.TextBoxFor().

您可以使用自定义编辑器模板Html.EditorFor()不是Html.TextBoxFor().

Create a new EditorTemplatesfolder in your /Views/Sharedfolder and add a new MVC 2 View User Controlnamed DateTime.ascx. Add the following

在您的/Views/Shared文件夹中创建一个新的EditorTemplates文件夹,并添加一个名为DateTime.ascx的新MVC 2 视图用户控件。添加以下内容

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%= Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty)) %>

Then in your view use

然后在您看来使用

<%= Html.EditorFor(model => model.BirthDate)%></p>

Don't worry about the "", the naming will still work correctly.

不要担心“”,命名仍然可以正常工作。

If you are displaying the DateTime in a different culture format to the default application culture then you will need to change the culture informationor alternatively create a custom model binderin order for the model binding to work when posting back the DateTime.

如果您以与默认应用程序文化不同的文化格式显示 DateTime,则您需要更改文化信息或创建自定义模型绑定器,以便模型绑定在回发 DateTime 时工作。

回答by joym8

MVC4 http://msdn.microsoft.com/en-us/library/hh833694.aspx

MVC4 http://msdn.microsoft.com/en-us/library/hh833694.aspx

@Html.TextBoxFor(model => model.YOUR_DATE, "{0:MM/dd/yyyy}")

回答by Serhiy

First, add this extension for getting property path:

首先,添加此扩展以获取属性路径:

public static string GetPropertyPath<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> property)
{                       
     Match match = Regex.Match(property.ToString(), @"^[^\.]+\.([^\(\)]+)$");
     return match.Groups[1].Value;
}

Than add this extensions for HtmlHalper:

比为 HtmlHalper 添加这个扩展:

public static MvcHtmlString DateBoxFor<TEntity>(
            this HtmlHelper helper,
            TEntity model,
            Expression<Func<TEntity, DateTime?>> property,
            object htmlAttributes)
        {
            DateTime? date = property.Compile().Invoke(model);

            // Here you can format value as you wish
            var value = date.HasValue ? date.Value.ToShortDateString() : string.Empty;
            var name = ExpressionParseHelper.GetPropertyPath(property);

            return helper.TextBox(name, value, htmlAttributes);
        }

Also you should add this jQuery code:

您还应该添加此 jQuery 代码:

$(function() {
    $("input.datebox").datepicker();
});

datepicker is a jQuery plugin.

datepicker 是一个 jQuery 插件。

And now you can use it:

现在你可以使用它:

 <%= Html.DateBoxFor(Model, (x => x.Entity.SomeDate), new { @class = "datebox" }) %>

回答by Cephas

It's a dirty hack, but it seems to work.

这是一个肮脏的黑客,但它似乎有效。

<%= Html.TextBoxFor(model => model.SomeDate,
    new Dictionary<string, object> { { "Value", Model.SomeDate.ToShortDateString() } })%>

You get the model binding, and are able to override the HTML "value" property of the text field with a formatted string.

您获得模型绑定,并且能够使用格式化字符串覆盖文本字段的 HTML“值”属性。

回答by Ashraf Alam

You can consider the following sample of TextBoxFor Extension method for datetime data:

您可以考虑以下用于日期时间数据的 TextBoxFor 扩展方法示例:

    public static MvcHtmlString CalenderTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            Func<TModel, TProperty> deleg = expression.Compile();
            var result = deleg(htmlHelper.ViewData.Model);

            string value = null;

            if (result.ToString() == DateTime.MinValue.ToString())
                value = string.Empty;
            else
                value = string.Format("{0:M-dd-yyyy}", result);

            return htmlHelper.TextBoxFor(expression, new { @class = "datepicker text", Value = value });
       }

回答by Bhavin hah

Just name it what it is looking for. Like:

只需命名它要查找的内容即可。喜欢:

Html.TextBox("Person.StartTime",Person.StartTime.ToShortDateString());

When it returns to the controller, your model will have the value bounded.

当它返回到控制器时,您的模型将具有有界值。

回答by Guillaume Roy

Have you tried to force the culture of your current thread application? You can override it in the web.config using this line (in the tag) :

您是否尝试过强制您当前线程应用程序的文化?您可以使用以下行(在标记中)在 web.config 中覆盖它:

<!-- Default resource files are set here. The culture will also change date format, decimal, etc... -->
<globalization enableClientBasedCulture="false" culture="en-US" uiCulture="en-US"/>

回答by nkirkes

I use some custom helpers and have used them successfully in MVC 2 and 3 (code also on Snipplr). The helpers have some css logic thrown in as I use the jQuery-ui datepicker, but that can easily be removed.

我使用了一些自定义助手,并在 MVC 2 和 3 中成功使用了它们(代码也在Snipplr 上)。当我使用 jQuery-ui datepicker 时,助手会加入一些 css 逻辑,但可以轻松删除。

public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString, object htmlAttributes)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        string format = String.IsNullOrEmpty(formatString) ? "M/d/yyyy" : formatString;
        DateTime date = metadata.Model == null ? new DateTime() : DateTime.Parse(metadata.Model.ToString());
        string value = date == new DateTime() ? String.Empty : date.ToString(format);
        RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes);
        string datePickerClass = "date-selector";
        if (attributes.ContainsKey("class"))
        {
            string cssClass = attributes["class"].ToString();
            attributes["class"] = cssClass.Insert(cssClass.Length, " " + datePickerClass);
        }
        else
        {
            attributes["class"] = datePickerClass;
        }
        return helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes);
    }

    public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
    {
        return DateTextBoxFor<TModel, TValue>(helper, expression, String.Empty, null);
    }

    public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString)
    {
        return DateTextBoxFor<TModel, TValue>(helper, expression, formatString, null);
    }

回答by andersjanmyr

A simple solution is to not use the strongly typed helper.

一个简单的解决方案是不使用强类型助手。

<%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %>

回答by CRice

Seriously, why should the view have to do this?

说真的,为什么视图必须这样做?

Map your core model which has the date time object to your mvc view model.

将具有日期时间对象的核心模型映射到 mvc 视图模型。

//core model
public class Person
{
    public DateTime? BirthDate { get; set;}
}

//view model
public class PersonForm
{
    public string BirthDate { get; set; }
}

So mapping might look like:

所以映射可能看起来像:

public interface IDomainToViewMapper<TModel, TViewModel>
{
    /// <summary>
    /// Use an automapper or custom implementation to map domain model to presentation model.
    /// </summary>
    /// <param name="source">domain model</param>
    /// <returns>presentation model</returns>
    TViewModel MapDomainToView(TModel source);        
}

public interface IPersonMapper : IDomainToViewMapper<Person, PersonForm>
{
}

public class PersonMapper : IPersonMapper
{
    #region IDomainToViewMapper<Person,PersonForm> Members

    public PersonForm MapDomainToView(Person source)
    {
        PersonForm p = new PersonForm();

        if (source.BirthDate.HasValue)
        {
            p.BirthDate = source.BirthDate.Value.ToShortDateString();
        }

        return p;
    }

    #endregion
}

And your controller action might look like:

您的控制器操作可能如下所示:

    public ActionResult Index()
    {
        Person person = //get person;
        var personForm = _personMapper.MapDomainToView(person);

        return View(personForm)
    }

You won't have to change your view example at all then.

那时您根本不必更改视图示例。



From Chapter 2, MVC 2 in Action (Manning)

来自第 2 章,MVC 2 实战(Manning)

public class CustomerSummary
{
public string Name { get; set; }
public bool Active { get; set; }
public string ServiceLevel { get; set; }
public string OrderCount { get; set;}
public string MostRecentOrderDate { get; set; }
}

This model is intentionally simple; it consists mostly of strings. That's what we're representing, after all: text on a page. The logic that displays the data in this object will be straightforward; the view will only output it. The presentation model is designed to minimize decision making in the view.

这个模型故意简单;它主要由字符串组成。毕竟,这就是我们所代表的:页面上的文本。显示此对象中数据的逻辑很简单;视图只会输出它。演示模型旨在最大限度地减少视图中的决策。