我从Where did the clear button go on date type input elements in Chrome? 的简单示例开始。
<input id=el type=datetime-local value="2025-07-01T12:44">
<button onclick="javascript:el.value=''">X</button>
并将其变成我的 C# ASP.NET Web 应用程序中的扩展方法。
public static System.Web.IHtmlString editorWithClearFor<TModel, TValue>(
this System.Web.Mvc.HtmlHelper<TModel> helper,
System.Linq.Expressions.Expression<Func<TModel, TValue>> expression,
object additionalViewData )
{
//------------------------------
// Determine the input element ID.
// The ID might be the property name.
ModelMetadata metadata = ModelMetadata.FromLambdaExpression( expression, helper.ViewData );
string inputElemId = metadata.PropertyName;
//------------------------------
// The ID might be specified in the HTML attributes within the view data.
Type t = additionalViewData.GetType();
PropertyInfo pi = t.GetProperty( "htmlAttributes" );
IDictionary<string, object> attribs = pi.GetValue( additionalViewData, null ) as IDictionary<string, object>;
if ( attribs.ContainsKey( "id" ) )
{
inputElemId = attribs["id"].ToString();
}
//------------------------------
// For the input and the button to be side by side,
// must I must wrap each of them in a div? That seems to be the only thing that works.
//------------------------------
// Input.
IHtmlString input = helper.EditorFor( expression, additionalViewData );
//------------------------------
// Wrap the input in a div.
TagBuilder div1 = new TagBuilder( "div" );
div1.MergeAttribute( "style", "display: inline-block;" );
div1.InnerHtml = input.ToString();
//------------------------------
// Clear button.
TagBuilder btn = new TagBuilder( "button" );
btn.MergeAttribute( "title", "Clear" );
btn.MergeAttribute( "style", "border: none; background-color: transparent;" );
btn.MergeAttribute( "onclick", String.Format( "javascript:{0}.value=''", inputElemId ) );
btn.InnerHtml = "X";
//------------------------------
// Wrap the button in a div.
TagBuilder div2 = new TagBuilder( "div" );
div2.MergeAttribute( "style", "display: inline-block;" );
div2.InnerHtml = btn.ToString();
//------------------------------
// Concatenate.
Debug.WriteLine( div1.ToString() + div2.ToString() );
return MvcHtmlString.Create( div1.ToString() + div2.ToString() );
}
cshtml 标记中的使用示例:
@Html.editorWithClearFor( m => m.DueDate, new { htmlAttributes = new { "class", "form-control" } } )