Date coming up as 12/30/1899 in MVC 4 - asp.net-mvc-4

In my model I have:
[DisplayName("Title Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = ("{0:d}"))]
public Nullable<System.DateTime> DateOfTitle { get; set; }
My View has:
<td>#Html.DisplayFor(modelItem => Model.DateOfTitle)</td>
The value in the database for this field is null. I would like the DisplayFor to show nothing unless there is a valid date for this field. It displays as 12/30/1899.

Try using this..
[DisplayFormat(NullDisplayText = "",
ApplyFormatInEditMode = true, DataFormatString = ("{0:d}"))]

Related

FluentValidation check start date greater than end date

I have this C# code with FluentValidation rule which check start date should be less than end date. When I run to put start date greater than end date, it should show error "End date must after Start date".
RuleFor(r => r.StartDate)
.NotEmpty()
.WithMessage("Start Date is Required");
RuleFor(r => r.EndDate)
.NotEmpty().WithMessage("End date is required")
.GreaterThan(r => r.StartDate.Value)
.WithMessage("End date must after Start date")
.When(m => m.StartDate.HasValue);
In my model, these 2 properties defined as below:
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
public DateTime? EndDate { get; set; }

Date formatting in MVC view

I have below entity in a mvc model:
[Display(Name = "Date Of Birth")]
public DateTime? DateOfBirth { get; set; }
and I am using it in a view as:
<td title="#u.CreatedDate">
#if (#u.DateOfBirth != null)
{
#u.DateOfBirth
}
</td>
This is working piece of code but I want to show this date in dd/mm/yyyy format.
I have tried something like this:
1. string.Format("dd/MM/yyyy", u.DateOfBirth);
2. [Display(Name = "Date Of Birth")]
[DisplayFormat (DataFormatString="dd/MM/yyyy")]
public DateTime? DateOfBirth { get; set; }
But nothing works fine for me. Please help
3 options you can use
#Html.DisplayFor(m => u.DateOfBirth) // assumes you have [DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]
#String.Format("{0:dd/MM/yyyy}", u.DateOfBirth)
#u.DateOfBirth.Value.ToString("dd/MM/yyyy")
In the first 2 cases, you do not need the #if (#u.DateOfBirth != null) check

How to get default selection into selectlist MVC

I need to use dropdownlist into razor and related object into model object.
I want to keep default selected value for the object but it did not work out.
Can any one suggest me what should be the best way to achieve this - what to keep into DTO property and controller action and razor syntax.
Below is my current stuff:
public class StateDTO
{
public int ID { get; set; }
public string Name { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name", Order = 2)]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password", Order = 3)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password", Order = 4)]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Display(Name = "Email Address", Order = 1)]
[DataType(DataType.EmailAddress)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Please enter value")]
public string Email { get; set; }
public IEnumerable<SelectListItem> States { get; set; }
public SelectListItem State { get; set; }
}
public ActionResult Register()
{
RegisterModel r = new RegisterModel();
IList<StateDTO> s = new List<StateDTO>();
s.Add(new StateDTO() { ID = 1, Name = "CA" });
s.Add(new StateDTO() { ID = 2, Name = "LA" });
s.Add(new StateDTO() { ID = 3, Name = "AR" });
r.State = new SelectListItem() { Text = s[2].Name, Value = s[2].ID.ToString(), Selected = true };
r.States = new SelectList(s, "ID", "Name",r.State);
return View(r);
}
View contains below related stuff:
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.State, Model.States)
#Html.ValidationMessageFor(model => model.State)
</div>
Please suggest me what should I change into Model object, controller and razor view to achieve default selection of dropdown list... any best way.
Thank You
I have modified the stuff as follow the below link and it worked out.
dropdownlist set selected value in MVC3 Razor
In model, changed the property type as follow:
public IEnumerable<SelectListItem> States { get; set; }
public int State { get; set; }
Controller action:
IList<StateDTO> s = new List<StateDTO>();
s.Add(new StateDTO() { ID = 1, Name = "CA" });
s.Add(new StateDTO() { ID = 2, Name = "LA" });
s.Add(new StateDTO() { ID = 3, Name = "AR" });
r.State = 3;
r.States = new SelectList(s, "ID", "Name",3);
View is as follow:
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.State, Model.States)
#Html.ValidationMessageFor(model => model.State)
</div>
It works...got default selection.
Thank you

Dropdown List MVC 4 error

I am trying to get a drop down list to work but its not working for me. This application is mainly a festival based application where you can add a festival along with your events. The error I am getting is on line:
#Html.DropDownList("towns", (IEnumerable<SelectListItem>)ViewData["Town"], new{#class = "form-control", #style="width:250px" })
This is the error I get:
There is no ViewData item of type 'IEnumerable' that has the key 'towns'.
Create.cshtml
<div class="form-group">
#Html.LabelFor(model => model.FestivalTown, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("towns", (IEnumerable<SelectListItem>)ViewData["Town"], new{#class = "form-control", #style="width:250px" })
#Html.ValidationMessageFor(model => model.FestivalTown)
</div>
#*#Html.Partial("ddlFestivalCounty");*#
</div>
Controller.cshtml
//Get
List<SelectListItem> Towns = new List<SelectListItem>();
Towns.Add(new SelectListItem { Text = "Please select your Town", Value = "SelectTown" });
var towns = (from t in db.Towns select t).ToArray();
for (int i = 0; i < towns.Length; i++)
{
Towns.Add(new SelectListItem
{
Text = towns[i].Name,
Value = towns[i].Name.ToString(),
Selected = (towns[i].ID == 0)
});
}
ViewData["Town"] = Towns;
//Post
festival.FestivalTown.Town = collection["Town"];
Model.cs
public class Festival
{
public int FestivalId { get; set; }
[Required]
[Display(Name = "Festival Name"), StringLength(100)]
public string FestivalName { get; set; }
[Required]
[Display(Name = "Start Date"), DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Required]
[Display(Name = "End Date"), DataType(DataType.Date)]
public DateTime EndDate { get; set; }
[Required]
[Display(Name = "County")]
public virtual County FestivalCounty { get; set; }
[Display(Name = "Festival Location")]
public DbGeography Location { get; set; }
[Required]
[Display(Name = "Town")]
public virtual Town FestivalTown { get; set; }
[Required]
[Display(Name = "Festival Type")]
public virtual FestivalType FType { get; set; }
public UserProfile UserId { get; set; }
}
public class Town
{
public int ID { get; set; }
[Display(Name = "Town")]
public string Name { get; set; }
}
I suspect that this error occurs when you submit the form to the [HttpPost] action and not when you are rendering the form, right? And this action renders the same view containing the dropdown, right? And inside this [HttpPost] action you forgot to populate the ViewData["Town"] value the same way you did in your HttpGet action, right?
So, go ahead and populate this property the same way you did in your GET action. When you submit the form to your [HttpPost] action, only the selected value is sent to the controller. So you need to repopulate the collection values if you intend to redisplay the same view, because this view renders a dropdown which is attempting to bind its values from ViewData["Town"].
And here's what I mean in terms of code:
[HttpPost]
public ActionResult SomeAction(Festival model)
{
... bla bla bla
// don't forget to repopulate the ViewData["Town"] value the same way you did in your GET action
// if you intend to redisplay the same view, otherwise the dropdown has no way of getting
// its values
ViewData["Town"] = ... same stuff as in your GET action
return View(model);
}
And all this being said, I would more than strongly recommend you using view models instead of this ViewData/ViewBag weakly typed stuff. Not only that your code will become much more clean, but even the error messages will start making sense.

Time Input Field in ASP.NET MVC

I'm having trouble trying to write a form with time field using ASP.NET MVC 4.
Model:
class Abcde {
[DataType(DataType.Time)]
public DateTime ATime { get; set; }
}
View.cshtml
...
#Html.EditorFor(m => m.ATime)
#Html.ValidationMessageFor(m => m.ATime)
The validation always failed when I tried to input a time (hh:nn:ss), and said it was not in the corrent format, so i have to input a date instead.
My Question is should I change the type to TimeSpan? Or is there any other way?
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:H:mm}")]
public DateTime Time { get; set; }`
Try this, you can format in the DataFormatString the way you want it to work for you, im using it in a project now and it's working for me.
Actually this is what worked for me.
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Hour { get; set; }
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm}")]
public DateTime Time { get; set; }
This code is correct. But it only works when you use EditorFor instead of TextBoxFor.
Use:
[Required]
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:HH:mm:ss}")]
public DateTime FieldTime{ get; set; }
You need to match your date validation with the format that works internally for this annotation. So, adding the ApplyFormat passing a String Pattern you can get it.