How can I use DisplayFormat data annotation in WebGrid columns? - asp.net-mvc-3

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")); }))

Related

How to format date in partial view MVC

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.

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.

Remove default value for non nullable properties when using EditFor [asp.net mvc 3]

How can I remove the default value that is added by default to the textboxes of non nullable properties when using the EditFor helper? I don't want that behavior
EDIT
Sorry I didn't give enough information.
For example if you use Html.EditorFor with a property that is DateTime it will set the textbox value to 1/1/0001 automatically. If you use "DateTime?"(nullable), it won't, it just leaves the textbox empty.
You can use UIHint to do it.
Create a file called ShortDate.cshtml in EditorTemplates
#model DateTime
#{ var value = Model == default(DateTime) ? null : Model.ToShortDateString(); }
#Html.TextBox(string.Empty, value)
Decorate your property with the UIHintAttribute referencing our EditorTemplate. Consider my Order class.
public class Order {
[UIHint("ShortDate")]
public DateTime Date { get; set; }
}
When you use
#Html.EditorFor(x => x.Date)
it should avoid the default value of DateTime
caveat: I just did simple tests, so please take a deep look into it.
hope it helps you
I had to do something like this for my own needs. I used this:
#model DateTime?
#Html.TextBox("", (Model.Value != default(DateTime) ? Model.Value.ToShortDateString() : string.Empty))
and it worked pretty nicely for my DateTime values. Ones that didn't have the default value are blank and the ones that have some other DateTime value show the ShortDateString representation of the object.

Resources