ASP.NET MVC2 and DateTime Format - asp.net-mvc

I am using ASP.NET MVC2 with MvcContrib.FluentHtml to do form binding.
I want to bind a DateTime format to a textbox with specific datetime format.
<%=this.TextBox(c => c.date_a).Class("readonly text-box") %>
// PS. c.date_a is a DateTime
gives me
<input type="text" value="5/9/2009 12:00:00 AM" name="date_a" id="datea" class="readonly text-box">
However, I'd like to override the default datetime format.
e.g.
value="2009-5-9"
value="9-5-09"
value="09May9"
I know I can override the value by specific a value, however, the date should also bind to the object class on POST the form.
How to do "minimum" code to override the default datetime format of a specific field on UI?

I don't know if this work with MvcContrib MvcContrib.FluentHtml but without it, it is very simple, add to your model property
[DisplayFormat(DataFormatString="{0:MM/dd/yyyy}", ApplyFormatInEditMode=true)]
and in your view
m.DateProperty) %>
I Don't know if MvcContrib uses Attributes but if it doesn't, it should, that way, you'll always have your date the same format, specifying the format only once...
hope this help

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:
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);
}
Also you should add this jQuery code:
$(function() {
$("input.datebox").datepicker();
});
datepicker is a jQuery plugin.
And now you can use it:
<%= Html.DateBoxFor(Model, (x => x.Entity.SomeDate), new { #class = "datebox" }) %>

I often run into situations where it's impractical to modify the model (with attributes etc) so being able to implement a solution like Сергій's is important. To Dennis Cheung point though, you can more tightly bind this solution as follows:
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);
}
Then you call it like this:
<%:Html.DateBoxFor(m => m.SomeDate)%>
Or like this:
<%:Html.DateBoxFor(m => m.SomeDate, "d", null)%>

With FluentHtml you can do like this:
<%=this.TextBox(c => c.date_a).Class("readonly text-box").Format("yyyy-M-d") %>

I am not sure whether this would cause you problems when the value is posted back but the following syntax should allow you to change the format with which the date value is displayed.
<%=this.TextBox(c => c.date_a.ToString('yyyy-M-d')).Class("readonly text-box") %>
You will find further information on how to construct the format strings here.

Related

DisplayFormat for TextBoxFor in MVC

I need to round off 4 digit decimal to 2 digits and show in MVC 3 UI
Something like this 58.8964 to 58.90
Tried following this How should I use EditorFor() in MVC for a currency/money type? but not working.
As i am using TextBoxFor=> i removed ApplyFormatInEditMode here. Even
i tried with ApplyFormatInEditMode , but nothing works. Still showing
me 58.8964.
MyModelClass
[DisplayFormat(DataFormatString = "{0:F2}")]
public decimal? TotalAmount { get; set; }
#Html.TextBoxFor(m=>m.TotalAmount)
How can i achieve this round off?
I can't use EditorFor(m=>m.TotalAmount) here, as i need to pass some htmlAttributes
Edit:
After debugging with MVC source code, they internally use
string valueParameter = Convert.ToString(value, CultureInfo.CurrentCulture);
in MvcHtmlString InputHelper() method of InputExtension.cs that takes object value as parameter and converting. They are not using any display format there. How could we fix?
I managed to fix in this way. As i have a custom helper, i can able to manage with the below code
if (!string.IsNullOrEmpty(modelMetaData.DisplayFormatString))
{
string formatString = modelMetaData.DisplayFormatString;
string formattedValue = String.Format(CultureInfo.CurrentCulture, formatString, modelMetaData.Model);
string name = ExpressionHelper.GetExpressionText(expression);
string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
return htmlHelper.TextBox(fullName, formattedValue, htmlAttributes);
}
else
{
return htmlHelper.TextBoxFor(expression, htmlAttributes);
}
This works in MVC5
#Html.TextBoxFor(m => m.TotalAmount, "{0:0.00}")
You should use Html.EditorFor instead of Html.TextBoxFor if you want the custom format to be taken into account:
#Html.EditorFor(m => m.TotalAmount)
Also make sure that you have set ApplyFormatInEditMode to true:
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }
The DisplayFormat attribute is intended to be used only with templated helpers such as EditorFor and DisplayFor. This is the recommended approach instead of using TextBoxFor.
Try like this:
#{
var format = String.Format("{0:0.00}", Model.TotalAmount);
}
#Html.TextBoxFor(m => m.TotalAmount, format)
Hope it helps.
If you need more control of the field being displayed (vs. a built in EditorFor template) create a custom EditorFor template yourself. Inside an EditorFor template, the built in Html Helpers like #Html.TextBox() can be used with automatic client side validation and Display attributes which are usually only available to EditorFor and DisplayFor.
For example looping through a List of items. The input name has to have an unbroken index.
// Optional, if you require a custom input name for binding
String fieldName = String.Format("FieldNameForBinding[{0}].Property", index)
#Html.EditorFor(m => m.Property, "MyCustomEditorTemplate", fieldName)
Then you can setup your model
[CustomValidation(..optional..)]
[DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
public decimal? TotalAmount { get; set; }
The EditorFor template (in e.g. ~/Views/Shared/EditorFor/MyCustomEditorTemplate.cshtml)
Note the name is left empty, it comes from the fieldName automatically. You can see it in the ViewData.TemplateInfo.HtmlFieldPrefix. Now you have complete control over the display of the field.
#model object
#{
Decimal? actualValue = (Decimal?)Model;
}
// The TextBox and ValidationMessage "names" are empty, they are filled
// from the htmlFieldName given via the #Html.EditorFor() call.
#Html.TextBox("", actualValue, new { #class = "cssClass" })
#Html.ValidationMessage("")
The idea is that you can customize the input field however you would like, and use e.g. #Html.TextBox() which outside of a custom EditorFor template would not utilize the built in client-side validation. You don't need to use the custom naming of the input field, that was simply an example of the usefulness of this solution. You can customize the way the data is presented (CSS, etc.) instead of relying on the built in EditorFor templates.
I solve that issue in this way:
#Html.TextBoxFor(model => model.dtArrivalDate, ModelMetadata.FromLambdaExpression(model => model.dtArrivalDate, ViewData).EditFormatString)
or create next extension:
public static class HtmlExtensions
{
public static MvcHtmlString TextBoxWithFormatFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return htmlHelper.TextBoxFor(expression, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).EditFormatString, htmlAttributes);
}
}
But you need to set ApplyFormatInEditMode=true in DisplayFormatAttribute on your field.

how to add content to html.label in javascript asp.net mvc

I have a label as
<%= Html.Label("");%>
i want to add content to label at runtime, unfortunately it doesn't take any other parameter to create id property for it. can't i create id property for it just similar to asp:label
thanks,
michaeld
No need to use the HtmlHelper functions always and everywhere if they don't fit your need. They're just supposed to make your life easier, not harder. Use good ole HTML here:
<label id="id_for_label"></label>
If you want to keep using HtmlHelper functions you can always create your own extension methods.
For example:
public static class LabelHelper
{
private static string HtmlAttributes(object htmlAttributes)
{
var builder = new StringBuilder();
foreach (PropertyDescriptor descriptor in
TypeDescriptor.GetProperties(htmlAttributes))
{
builder.AppendFormat(" {0}=\"{1}\" ", descriptor.Name,
descriptor.GetValue(htmlAttributes));
}
return builder.ToString();
}
public static MvcHtmlString MyLabel(this HtmlHelper htmlHelper,
string labelText, object htmlAttributes)
{
var attributes = HtmlAttributes(htmlAttributes);
return MvcHtmlString.Create(
String.Format("<label for=\"{0}\" {1}>{0}</label",
labelText, attributes.Trim()));
}
}
Then you can add a label to a view in the following manner:
<%: Html.MyLabel("Hello, World!", new { #id = "myLabel" })%>
The generated HTML is:
<label for="Hello, World!" id="myLabel">Hello, World!</label>
For MVC 3 such a helper function is already available:
http://msdn.microsoft.com/en-us/library/gg538318(v=VS.99).aspx

ASP.NET MVC 3 Custom HTML Helpers- Best Practices/Uses

New to MVC and have been running through the tutorials on the asp.net website.
They include an example of a custom html helper to truncate long text displayed in a table.
Just wondering what other solutions people have come up with using HTML helpers and if there are any best practices or things to avoid when creating/using them.
As an example, I was considering writing a custom helper to format dates that I need to display in various places, but am now concerned that there may be a more elegant solution(I.E. DataAnnotations in my models)
Any thoughts?
EDIT:
Another potential use I just thought of...String concatenation.
A custom helper could take in a userID as input and return a Users full name...
The result could be some form of (Title) (First) (Middle) (Last) depending on which of those fields are available. Just a thought, I have not tried anything like this yet.
I use HtmlHelpers all the time, most commonly to encapsulate the generation of boilerplate HTML, in case I change my mind. I've had such helpers as:
Html.BodyId(): generates a conventional body id tag for referencing when adding custom css for a view.
Html.SubmitButton(string): generates either an input[type=submit] or button[type=submit] element, depending on how I want to style the buttons.
Html.Pager(IPagedList): For generating paging controls from a paged list model.
etc....
One of my favorite uses for HtmlHelpers is to DRY up common form markup. Usually, I have a container div for a form line, one div for the label, and one label for the input, validation messages, hint text, etc. Ultimately, this could end up being a lot of boilerplate html tags. An example of how I have handled this follows:
public static MvcHtmlString FormLineDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string labelText = null, string customHelpText = null, object htmlAttributes = null)
{
return FormLine(
helper.LabelFor(expression, labelText).ToString() +
helper.HelpTextFor(expression, customHelpText),
helper.DropDownListFor(expression, selectList, htmlAttributes).ToString() +
helper.ValidationMessageFor(expression));
}
public static MvcHtmlString FormLineEditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string templateName = null, string labelText = null, string customHelpText = null, object htmlAttributes = null)
{
return FormLine(
helper.LabelFor(expression, labelText).ToString() +
helper.HelpTextFor(expression, customHelpText),
helper.EditorFor(expression, templateName, htmlAttributes).ToString() +
helper.ValidationMessageFor(expression));
}
private static MvcHtmlString FormLine(string labelContent, string fieldContent, object htmlAttributes = null)
{
var editorLabel = new TagBuilder("div");
editorLabel.AddCssClass("editor-label");
editorLabel.InnerHtml += labelContent;
var editorField = new TagBuilder("div");
editorField.AddCssClass("editor-field");
editorField.InnerHtml += fieldContent;
var container = new TagBuilder("div");
if (htmlAttributes != null)
container.MergeAttributes(new RouteValueDictionary(htmlAttributes));
container.AddCssClass("form-line");
container.InnerHtml += editorLabel;
container.InnerHtml += editorField;
return MvcHtmlString.Create(container.ToString());
}
public static MvcHtmlString HelpTextFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string customText = null)
{
// Can do all sorts of things here -- eg: reflect over attributes and add hints, etc...
}
Once you've done this, though, you can output form lines like this:
<%: Html.FormLineEditorFor(model => model.Property1) %>
<%: Html.FormLineEditorFor(model => model.Property2) %>
<%: Html.FormLineEditorFor(model => model.Property3) %>
... and BAM, all your labels, inputs, hints, and validation messages are on your page. Again, you can use attributes on your models and reflect over them to get really smart and DRY. And of course this would be a waste of time if you can't standardize on your form design. However, for simple cases, where css can supply all the customization you need, it works grrrrrrrrreat!
Moral of the story -- HtmlHelpers can insulate you from global design changes wrecking hand crafted markup in view after view. I like them. But you can go overboard, and sometimes partial views are better than coded helpers. A general rule of thumb I use for deciding between helper vs. partial view: If the chunk of HTML requires a lot of conditional logic or coding trickery, I use a helper (put code where code should be); if not, if I am just outputting common markup without much logic, I use a partial view (put markup where markup should be).
Hope this gives you some ideas!
Well in the case of formatting the DisplayFormat attribute could be a nice solution:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime Date { get; set; }
and then simply:
#Html.DisplayFor(x => x.Date)
As far as truncating string is concerned a custom HTML helper is a good solution.
UPDATE:
Concerning your EDIT, a custom HTML helper might work in this situation but there's also an alternative approach which I like very much: view models. So if in this particular view you are always going to show the concatenation of the names then you could define a view model:
public class PersonViewModel
{
public string FullName { get; set; }
}
Now the controller is going to query the repository to fetch the model and then map this model to a view model which will be passed to the view so that the view could simply #Html.DisplayFor(x => x.FullName). The mapping between models and view models could be simplified with frameworks like AutoMapper.
public static HtmlString OwnControlName<T, U>(this HtmlHelper<T> helper, Expression<Func<T, U>> expression, string label_Name = "", string label_Title = "", Attr attr = null)
{
TemplateBuilder tb = null;
string template = null;
if (expression == null) throw new ArgumentException("expression");
obj = helper.ViewData.Model;
tb.Build(obj, expression.Body as MemberExpression, typeof(T), new SimpleTemplate(new TextArea()), label_Name, label_Title, attr);
template = tb.Get();
return new MvcHtmlString(template);
}

can i change the way LabelFor render in MVC?

i would like to change the way LabelFor render. Can i do that with a DisplayTemplate?
LabelFor generate a label tag and i would like to add a ":" at the end of the label.
thank you!
alex
Here is an HTML Helper that will do that:
public static class LabelExtensions {
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString SmartLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) {
return LabelHelper(html,
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression));
}
internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName) {
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText)) {
return MvcHtmlString.Empty;
}
// uncomment if want * for required field
//if (metadata.IsRequired) labelText = labelText + " *";
labelText = labelText + ":";
TagBuilder tag = new TagBuilder("label");
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
tag.SetInnerText(labelText);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
To use it:
<%:Html.SmartLabelFor(m => m.FirstName)%>
It will render:
<label for="FirstName">First Name:</label>
Or if you uncomment the required field related *
<label for="FirstName">First Name *:</label>
Just write a regular <label> element in plain HTML:
<label>My Label:</label>
If you want to output the for="" attribute and accurately render the control's name then use this extension method:
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
namespace MvcLibrary.Extensions
{
public static class HtmlExtensions
{
public static MvcHtmlString FieldIdFor<TModel, TValue>(
this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string inputFieldId = html.ViewContext.ViewData.
TemplateInfo.GetFullHtmlFieldId(htmlFieldName);
return MvcHtmlString.Create(inputFieldId);
}
}
}
Then you can use in your view like so:
<label for="<%= Html.FieldIdFor(m => m.EmailAddress) %>">E-mail address:</label>
<%= Html.TextBoxFor(m => m.EmailAddress) %>
The other posts cover different approaches, they are all equally valid, which one you go for is matter of personal preference. I personally prefer writing the <label> as plain HTML as it gives designers more flexibility with changing markup, adding extra attributes such as CSS classes etc. Also I feel the label text is a view concern and shouldn't be decorated on the ViewModel class, but that's just my personal opinion/preference, I know some people here will disagree with me and that's fine :-)
You can create a String.ascx in DisplayTemplates folder and provide your own implementation. Refer to the Overriding Templates section of the following article.
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
You could do this using MVC 2 (if possible) if you pass a custom ViewModel to the view.
using System.ComponentModel;
public class PersonViewModel
{
public PersonViewModel(string name)
{
this.Name = name;
}
[DisplayName(".Display Anything You Like Here.")]
public string Name { get; set; }
I think the best approach would be writing your own helper method that renders what you like. You can overload the existing method or simply create a new method.

ASP.Net MVC 2.0 Html.HiddenFor HtmlHelper extension doesn't return the Value

We're trying to be type-safe in our views and use the new ExpressionInputExtenssion HtmlHelpers, but we are seeing some inconsistent results. We have a view that looks like this:
ViewData.Model.FooID = <%= ViewData.Model.FooID %><
Model.FooID = <%= Model.FooID %>
<%= Html.HiddenFor(x=>x.FooID) %>
But what we see in the rendered view is this:
ViewData.Model.FooID = 515b0403-e75b-4bd7-9b60-ef432f39d338
Model.FooID = 515b0403-e75b-4bd7-9b60-ef432f39d338
<input id="FooID" name="FooID" type="hidden" value="" />
I can manually add this:
<input id="FooID" name="FooID" type="hidden" value="<%= Model.FooID %>" />
But now we are no longer, but surprisingly when I do, The Html.HiddenFor always has the correct value.
Take a look at this:
http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx
It looks like the model binder that is behind the extension method cannot convert you FoodID datatype to a string. Is your data type a regular GUID?
I known there are overloads for this extension method for working with binary but I'm not sure about GUIDs ....
Have u tried debbuging it?
I encountered similiar problem, I have one element of the model is hiddeninput, I can see the correct value of this element while displaying view(as debug I show it to check there's correct value in the view), but once I post the view, the return value of this element keeps the first time it's been set, whatever I refresh the display and be sure the correct value shown on the view, but the return value just keep the value been set at first time. This is odd.
You can also roll your own extension that use the value from the property
#Html.HiddenForField(m => m.Location.CityRequired)
public static class HiddenExtensions
{
public static MvcHtmlString HiddenForField<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression) where TModel : class
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var value = metadata.Model;
return htmlHelper.HiddenForField(expression, value);
}
public static MvcHtmlString HiddenForField<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object value) where TModel : class
{
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
var tag = new TagBuilder("input");
tag.GenerateId(fullName);
tag.Attributes.Add("type", "hidden");
tag.Attributes.Add("name", fullName);
tag.Attributes.Add("value", value != null ? value.ToString() : string.Empty);
return new MvcHtmlString(tag.ToString());
}
}

Resources