How to format date in partial view MVC - model-view-controller

I am currently developing asp.net core(Framework 3.1) application. I am getting date from database and storing it in string(tried using DateTime but didn't work). Here's my code in model:
public string TranDate { get; set; }
salesList.Add(new SalesData()
{
TranDate = dt.Rows[i]["TRANDATE"].ToString(),
});
It displays date in "2020/06/06 00:00:00" format.
In partial view:
<td>
#Html.DisplayFor(modelItem => item.TranDate)
</td>
Now I want to display date in "dd/MM/yyyy" format like "06/06/2020" in my partial view. I have tried many ways like display templates, editor templates, String.Format but nothing works. Please help!

Please try something like the following;
string formattedDate = DateTime.Now.ToShortDateString(); //set a default date
if (DateTime.TryParse(TranDate, out DateTime usersDate))
{
formattedDate = usersDate.ToShortDateString();
}
TranDate = formattedDate;
Some of this may be too much, but the core premise is that using the DateTime.TryParse method ensures that the date being passed into it (your "TranDate" parameter) can even be converted to a date. I know it is coming from the database and likely a Date field itself, but we really should not trust that, to be sure.

Related

ASP.NET MVC 4 avoid generation of data-val-date for datetime

how can I avoid the generation of the html attribute "data-val-date" for the element created from a Datetime property?
The model:
public class RegisterModel
{
[Required]
[Display(Name = "Date of birth")]
public DateTime? DateOfBirth { get; set; }
}
The view:
#Html.LabelFor(m => m.DateOfBirth)
#Html.EditorFor(m => m.DateOfBirth)
In fact, I'm creating a three drop down lists element for selecting the date of birth, which don't give a value in a date format.
Some solutions I've seen, consisted in a work around: removing the validation with a javascript.
The solution I envisage is to split the DateTime property into three long one for each value (day, month, year).
Ok, this took me an afternoon of work... apparently mvc4 decided that it was time to render a data-val-date="Message" on EVERY datetime property on the viewmodel. I've tried to modify this default behaviour but didn't succeed.
This solved my problems:
$.validator.addMethod('date',
function (value, element) {
return true; // since MVC4 data-val-date is put on EVERY vm date property. Default implementation does not allow for multiple cultures...
});
You can also try to write your own editor template named "DateTime.cshtml" in your shared EditorFor folder, but don't use TextBoxFor there, because that one is polluted as well.
data-val-date is used by the validation system to validate the date. If you remove it, client-side validation won't work.
If that's what you want, then just disable client-side validation.
Add this to your application start in your global.asax file and the form should fire.
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

use other instead of #Html.DisplayFor in asp.net mvc 3 razor view

I am novice to the asp.net mvc3. It's really confusing and difficult to modify single code due to convention used in asp.net mvc3. I was trying to display only Date for BirthDate in the format 5 Sep 1999 instead which shows Date and Time.It's fine in Edit.cshtml, datepicker is used to pick the date and value is saved in database of only date. But, I have BirthDate column of Data type of Date not the DateTime and when using #Html.DisplayFor(model => model.BirthDate); in Details.cshtml shows both date and time. While Searching in google I have found and implement following code for displaying date in desire format:
#Model.BirthDate.ToString("dd MMM YYYY");
and
#Html.DisplayFor(model => model.BirthDate.ToString("dd MMM YYYY"));
It gives error no overload method takes 1 argument. Further I could use like:
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
pubilc DateTime BirthDate { get; set }
Since, I have used model first approach for Entity Framework. Where Should I implement above DisplayFormat property or what may be razor syntax to display date in right way in Details.csthml in my scenario
ok, I know I'm replying to a question posted 8 month before but my only intention is, this might be useful to others refering this question in future.
I'm also novoice to MVC and I also faced a similar problem where I need to display only the date and not the time and following worked for me.
Instead of #Html.DisplayFor(). Use <span>
So, for the case mentioned in question it would be like this:
<span>#String.Format("{0:D}", model.BirthDate)</span>
Output: Sunday, September 05, 1999
No, need to add extra class/file for formating.
The third approach is the best way according to me cos
your presentation model is dealing with all the aspects of UI and your view doesnt have unnecessary and redundant formatting code especially if you reuse the property.
enables unit testing
Consistent across different pages if you reuse the model.
You could also write an helper method that formats the date and use this consistently across all your presentation/view models.
public string FormattedDate(this DateTime dateTime)
{
return dateTime.ToString("dd MMM YYYY");
}
I like using a kind of decorator pattern to handle this kind of thing. Let's say your model class is called MyModel. Then define a wrapper class like this:
public class MyModelDecorator
{
public MyModel BaseItem { get; set; }
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime BirthDate { get; set; }
public MyModelDecorator(MyModel baseItem)
{
BaseItem = baseItem;
}
}
Then in your Views, you can refer to either the base model properties, or to the decorated properties.
#Html.DisplayFor(m => m.BirthDate)
#Html.DisplayFor(m => m.BaseItem.SomeOtherProperty)
If there's a better solution than this one, then I'd really like to hear it....
For any ASPX user sumbad answer helped but this is how you do it:
<%=Html.Enconde(String.Format("{0:D}", item.yourDate))%>
Hope this helps someone.

JQuery Validation and MVC 3. How to change date format

I'm a newbie to MVC 3 and JQuery Validation so any help I can get here will be very much appreciated.
My devleopment platform is .NET MVC 3 website. I'm using the built in unobtrusive javascript for form validation. Is there a way to change the date to a different format for a valid date. As far as I can tell, the valid format is dd/mm/yy. Is it possible to change the valid date format to something like "Apr 3, 2012"?
My view model has a field
[Required]
DateTime OrderDate { get; set; }
I know that MVC 3 is using jquery validation under the hood so I'm thinking the solution will require a change to jquery validate and also not sure how to hook it up to MVC so it works like all the other built in data validations using data annotations.
Thank you.
When you use client side validation for date, you have to override the jQuery validation for date as well.
$.validator.methods.date = function (value, element) {
return this.optional(element) || Globalize.parseDate(value, "MMM dd, yyyy") !== null;
}
You have to reference the Globalize library and the appropriate culture in your HTML head. Download from https://github.com/jquery/globalize.
If you wanted to change the format of Order Date you would do so with the DisplayFormat annotation:
[DisplayName("Order Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yy}")]
[Required]
DateTime OrderDate { get; set; }
Where the DataFormatString is your desired date time format.

Passing a DateTime to controller via URL causing error in ASP .NET MVC 3 (culture)

My application is setted with pt-BR culture (Date is dd-mm-yyyy) in web.config:
<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" fileEncoding="iso-8859-15" responseHeaderEncoding="utf-8" resourceProviderFactoryType="string" enableBestFitResponseEncoding="true" culture="pt-BR" uiCulture="pt-BR" />
All DateTime created on my system is in right format, but I created a controller method like that:
public ActionResult Test(DateTime date)
{
}
Calling that method direct in the browser is passing null when the date is with portuguese-br format, like that:
mysite/Test/?date=19/01/2012 => date = null in my controller
mysite/Test/?date=01/01/2012 => date is fine, but in US format (mm-dd-yyyy)
How can I fix that, to accept my date format?
There's a gotcha with the default model binder that is not easy to know about but once you know it you no longer make the same mistake:
When you use a POST request, the default model binder uses your culture settings to parse the dates.
When you use a GET request, the default model binder uses CultureInfo.InvariantCulture to parse the dates and ignores your current culture settings.
Since you are using a GET request and passing the date as a query string parameter, you should format it using the invariant culture format when sending it in the url. The correct way to format your date as a query string parameter is yyyy-MM-dd.
You may take a look at the following blog post which gets into more details.
As someone who does a lot of work with US companies, I've had a lot of experience with date issues.
My best advice is to choose an unambiguous format when transmitting.
dd-MMM-yyyy
and
yyyy-MM-dd
Are safe bets, and will be successfully parsed by DateTime.Parse(obj).
If changing the date format is not an option, you should look at DateTime.ParseExact, which allows you to specify the exact format string you are after.
One approach would be to accept the date as a string and then manipulate it in the controller to the correct locale/culture.
Got the same problem using an #Html.Action(..) in a view. For this situation it can be solved by putting the DateTime in a model:
public class MyModel
{
public DateTime Value {get;set;}
}
and in the view:
#Html.Action("MyAction", new { myModel })
Note the new { } around the instance of MyModel, this way the DateTime is not converted to a string. This solution only works for Html.Action() and not for Html.ActionLink() or Url.Action() since MVC is doing a myModel.ToString() in the URL.

How can I use DisplayFormat data annotation in WebGrid columns?

I have the following property in my model:
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? Date { get; set; }
And I am trying to use the Html.DisplayFor helper to use this specification in a WebGrid column, like so:
Sources.Column("Date", "As Of Date", (item) => Html.DisplayFor(x => item))
When I run this, I get a lot of extra information in the column, and the date comes out as a long format date, instead of the desired short format. The output I get makes me suspect that DisplayFor is looking through each property in the model and printing it, instead of just looking at Date. Why would it do this? Is there something I can do to use DisplayFor in the WebGrid?
When I try to specify item.Date I get the error "An expression tree may not contain a dynamic operation"
Try this code snippet instead of what you have now:
Sources.Column( header: "Date", format: ( item -> { return #Html.Raw(item.date.ToString("d")); }))

Resources