Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"asp-format" not applied to tag helpers

I'm facing a problem using "asp-format" tag with taghelper element in my mvc 6 project.

The idea is to format a date input element this way:

<input asp-for="StartDate" asp-format="{0:dd/MM/yyyy}" />

This "StartDate" property is in my model, declared this way:

public DateTime StartDate {get; set; }

For a strange reason, this element is never formatted, and is presented always like this:

---> 02/29/2016 00:00:00

So I created a viewmodel class and defined a property to hold the entire person model.

public class PersonViewModel 
{
    public Person Johndoe {get; set; }
}

And using this class in the view, the formatting works.

<input asp-for="Johndoe.StartDate" asp-format="{0:dd/MM/yyyy}" />

---> 29/02/2016
like image 332
Beetlejuice Avatar asked Feb 29 '16 13:02

Beetlejuice


People also ask

What is ASP for tag helper?

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. Tag helpers are a new feature and similar to HTML helpers, which help us render HTML.

Can I use HTML tag helper of ASP NET framework in asp net core?

A Tag Helper Component is a Tag Helper that allows you to conditionally modify or add HTML elements from server-side code. This feature is available in ASP.NET Core 2.0 or later. ASP.NET Core includes two built-in Tag Helper Components: head and body . They're located in the Microsoft.

What is the difference between tag helper vs HTML helper?

Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.

What is label ASP for?

Its purpose is simply to generate a label element for a property on your model. You use it by adding the asp-for attribute to a label element. For example, given a model class with an Email property as follows: public class SimpleViewModel.


2 Answers

You can provide the format in model itself like

 [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]

  public DateTime StartDate {get; set; }

and in your view simply like

@Html.EditorFor(model=>model.StartTime)

2) You can also do this without providing date format in model class

@Html.TextBoxFor(m => m.StartDate, "{0:dd/MM/yyyy}")
like image 164
REDEVI_ Avatar answered Oct 10 '22 03:10

REDEVI_


Add type = date which will format the date

<input asp-for="StartDate" type="date" class="form-control" />
like image 29
preetam kumar Avatar answered Oct 10 '22 05:10

preetam kumar