Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime field and Html.TextBoxFor() helper. How to use it correctly?

Tags:

I have a DateTime field in my Model. If I try to use this field in a strong typed partial view this way

<%= Html.TextBoxFor(model => model.DataUdienza.ToString("dd/MM/yyyy"), new { style = "width: 120px" })  %> 

I will get the following compilation error at runtime

System.InvalidOperationException : Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. 

Anyway if I use it removing the formatting, ToString("dd/MM/yyyy"), everything works but the field is formatted using the time part which I dont need at all.

Where I am doing wrong? Which is the correct way to handle this?

thanks for helping!

EDIT

This is the property declaration in the model class

[Required] [DisplayName("Data Udienza")] [DataType(DataType.Date)] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")] public DateTime DataUdienza { get; set; } 
like image 477
Lorenzo Avatar asked Sep 17 '10 11:09

Lorenzo


People also ask

What is the difference between using HTML TextBoxFor and HTML textbox?

Both of them provide the same HTML output, “HTML. TextBoxFor” is strongly typed while “HTML. TextBox” isn't. Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.

What is HTML helper method?

An HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>, <button> and <img> tags etc.

Why we use HTML helpers in MVC?

Helper class can create HTML controls programmatically. HTML Helpers are used in View to render HTML content. It is not mandatory to use HTML Helper classes for building an ASP.NET MVC application. We can build an ASP.NET MVC application without using them, but HTML Helpers helps in the rapid development of a view.

What is TextBoxFor?

Returns a text input element for each property in the object that is represented by the specified expression, using the specified HTML attributes. TextBoxFor<TModel,TProperty>(HtmlHelper<TModel>, Expression<Func<TModel,TProperty>>, String, IDictionary<String,Object>) Returns a text input element.


1 Answers

i use this in mvc 4. it also works~

@Html.TextBoxFor(x => x.DatePurchase, "{0:yyyy-MM-dd}", new { @class = "dateInput", @placeholder = "plz input date" }) 
like image 149
DarkMFJ Avatar answered Sep 29 '22 12:09

DarkMFJ