ASP.NET MVC2 및 DATETIME 형식
-
19-09-2019 - |
문제
나는 mvccontrib.fluenthtml과 함께 asp.net mvc2를 사용하여 형태 바인딩을 수행하고 있습니다.
DateTime 형식을 특정 DateTime 형식의 텍스트 상자에 바인딩하고 싶습니다.
<%=this.TextBox(c => c.date_a).Class("readonly text-box") %>
// PS. c.date_a is a DateTime
나에게 준다
<input type="text" value="5/9/2009 12:00:00 AM" name="date_a" id="datea" class="readonly text-box">
그러나 기본 DateTime 형식을 무시하고 싶습니다. 예를 들어
value="2009-5-9"
value="9-5-09"
value="09May9"
특정 값으로 값을 무시할 수는 있지만 날짜는 양식 게시물의 객체 클래스에도 바인딩해야합니다.
UI에서 특정 필드의 기본 DateTime 형식을 무시하기 위해 "최소"코드를 수행하는 방법은 무엇입니까?
해결책
fluenthtml을 사용하면 다음과 같이 할 수 있습니다.
<%=this.TextBox(c => c.date_a).Class("readonly text-box").Format("yyyy-M-d") %>
다른 팁
MVCCONTRIB MVCCONTRIB.FLUENTHTML과 함께 작동하는지 모르겠지만, 그 없이는 매우 간단합니다. 모델 속성에 추가하십시오.
displayFormat (dataformatstring = "{0 : mm/dd/yyyy}", applyformatedItmode = true)
그리고 당신의 견해로
M.DateProperty) %>
MVCContrib이 속성을 사용하는지 여부는 모르겠지만 그렇지 않은 경우 그렇게해야합니다. 그렇게해야합니다. 그렇게해야합니다. 그렇게해야합니다. 항상 동일한 형식을 사용하여 형식을 한 번만 지정해야합니다 ...
이 도움을 바랍니다
먼저 속성 경로를 얻기 위해이 확장자를 추가하십시오.
public static string GetPropertyPath<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> property)
{
Match match = Regex.Match(property.ToString(), @"^[^\.]+\.([^\(\)]+)$");
return match.Groups[1].Value;
}
htmlhalper 에이 확장을 추가하는 것보다 :
public static MvcHtmlString DateBoxFor<TEntity>(
this HtmlHelper helper,
TEntity model,
Expression<Func<TEntity, DateTime?>> property,
object htmlAttributes)
{
DateTime? date = property.Compile().Invoke(model);
var value = date.HasValue ? date.Value.ToShortDateString() : string.Empty;
var name = ExpressionParseHelper.GetPropertyPath(property);
return helper.TextBox(name, value, htmlAttributes);
}
또한이 jQuery 코드를 추가해야합니다.
$(function() {
$("input.datebox").datepicker();
});
DatePicker는 jQuery 플러그인입니다.
이제 사용할 수 있습니다.
<%= Html.DateBoxFor(Model, (x => x.Entity.SomeDate), new { @class = "datebox" }) %>
나는 종종 모델 (속성 등)을 수정하는 것이 비현실적 인 상황에 빠지기 때문에 сергій와 같은 솔루션을 구현할 수있는 것이 중요합니다. 그러나 Dennis Cheung Point에게는이 솔루션이 다음과 같이 더 단단히 바인딩 할 수 있습니다.
public static MvcHtmlString DateBoxFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, DateTime?>> property)
{
return helper.DateBoxFor(property, "d", null);
}
public static MvcHtmlString DateBoxFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, DateTime?>> property, string format, object htmlAttributes)
{
var viewData = helper.ViewContext.ViewData;
var date = property.Compile().Invoke(viewData.Model);
var value = date.HasValue ? date.Value.ToString(format) : string.Empty;
var name = viewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(property));
return helper.TextBox(name, value, htmlAttributes);
}
그런 다음 다음과 같이 부릅니다.
<%:Html.DateBoxFor(m => m.SomeDate)%>
또는 이렇게 :
<%:Html.DateBoxFor(m => m.SomeDate, "d", null)%>
값이 다시 게시 될 때 이것이 문제를 일으킬지 확실하지 않지만 다음 구문을 사용하면 날짜 값이 표시되는 형식을 변경할 수 있습니다.
<%=this.TextBox(c => c.date_a.ToString('yyyy-M-d')).Class("readonly text-box") %>
형식 문자열을 구성하는 방법에 대한 추가 정보를 찾을 수 있습니다. 여기.