I have a textbox on my view and I'm only looking it to display the current date and time(in readonly..how can this be done?
Currently I have this in the view:
<div class="editor-field">
#Html.EditorFor(model => model.Opened, new { #value = System.DateTime.Now, #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Opened)
</div>
..And this in the model:
[Required]
public DateTime Opened
{
get;
set;
}
How can this be implemented in MVC?
Thanks,
I recommend you using a Label. I think it's unusual display dates and time at TextBoxes.
Regards.
Well, you can do that, but #Angel Manuel Garcia Car's suggest is what you should be doing logically.
Anyways, here is the code. As long as you are creating a textbox, you should be using TextBoxFor.
#Html.TextBoxFor(model => model.Opened, new { #value = DateTime.Now, #readonly="readonly" })
I don't see any point here.
Related
I am trying to properly display a (nullable) Date-type-only field. For this field, my Model and ViewModel classes are defined as....
[DisplayFormat(DataFormatString = "{0:M/dd/yyyy}")]
[DataType(DataType.Date)]
public DateTime? PeriodEnd { get; set; }
In my details view (based on model), it's showing the date properly (excluding the time element):
#Html.DisplayNameFor(model => model.PeriodEnd)
Problem: In my edit view (based on ViewModel), it's showing the time also, which I'm trying to exclude. Here's how it's defined.
#Html.TextBoxFor(model => model.PeriodEnd, new { #class = "datepicker" })
I also tried....
#Html.TextBoxFor(model => model.PeriodEnd.Value().ToShortDateString(),
new { #class = "datepicker" })
... but that produced an error.
Is there a better way to accomplish this?
Well, first, you're not utilizing the data annotation. Something like DataType.Date doesn't do anything on its own. Using editor templates (Html.EditorFor), it can be utilized to provide an date type input, but if you use Html.TextBoxFor, it's basically ignored.
You can fix that by either 1) using Html.EditorFor instead or 2) explicitly setting the type: #Html.TextBoxFor(m => m.PeriodEnd, new { type = "date", #class = "datepicker" }).
This was the solution:
#Html.TextBoxFor(m => m.PeriodEnd, "{0:M/d/yyyy}", new { #class = "datepicker" })
Thanks to all for your feedback!
I am trying to save the date the user enters into a database. The problem is that despite only the date showing in the text box the time is also being saved. This is what it looks like in my model.
{11/02/2015 00:00:00}
However this is what I have in my JQuery set up and how I would like it to look when saved to the database, without the time also attached.
$("#datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
I assume the problem lies in my model somewhere so this is how I have it set up at the moment.
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DateOfBooking { get; set; }
and this is my view,
<div class="form-group">
#Html.LabelFor(model => model.DateOfBooking, new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.TextBoxFor(x => x.DateOfBooking, new { #id = "datepicker" })
#Html.ValidationMessageFor(model => model.DateOfBooking)
</div>
</div>
There's no way, using DateTimes, to only store/pass the date to the model. In SQL you can use a Date data type that will only store the Date part of the DateTime object from .Net. However, when you move data into/out of your model you'll always have a time component. The easiest way is to just ignore the time component and specify the display format like you're doing.
You could also use something like Noda Time that has structs for Date only types.
I have an application that warrants the need for users to supply a "best fit time of day" for a particular day of week. I am trying to represent that time of day as the timespan object in C# (just as the DateTime.TimeOfDay object does) I don't need the date, but also don't want to use datetime and have the user see an actual date.
Right now i have this in my model:
[Required, Display(Name = "Start")]
public TimeSpan StartTime { get; set; }
[Required, Display(Name = "End")]
public TimeSpan EndTime { get; set; }
I have this for part of my view:
<div class="form-group col-xs-6 col-lg-4">
#Html.LabelFor(m => m.StartTime, new { #class = "control-label" })
#(Html.Kendo().TimePickerFor(m => m.StartTime).Interval(15).Culture("en-Us").HtmlAttributes(new { #class = "form-control" }))
#Html.ValidationMessageFor(m => m.StartTime)
</div>
<div class="clearfix"></div>
<div class="form-group col-xs-6 col-lg-4">
#Html.LabelFor(m => m.EndTime, new { #class = "control-label" })
#(Html.Kendo().TimePickerFor(m => m.EndTime).Interval(15).Culture("en-Us").HtmlAttributes(new { #class = "form-control" }))
#Html.ValidationMessageFor(m=>m.EndTime)
</div>
<div class="clearfix"></div>
I keep getting this model error using the MVC ModelState:
ErrorMessage = "The value '1:00 PM' is not valid for Start."
I'm not sure what i'm doing wrong, intellesense says that the kendo widget supports a timespan for it's input, but why isn't this actually binding to the view?
i have seen this article: Kendo Timepickerfor formatting not working
It's not quite what i'm looking for, because i feel like there should be a more simple way to represent a time of the day that is unrelated to the actual date...
Any help is greatly appreciated!
Thanks!
Using DateTime seemed to work like you had said #Saranga
Not too thrilled it stores the entire date in the database, as it's not immediately clear then that this is only relevant to the time only, but it works.
Thanks for your help!
My model has a object which has a date property...
[Required(ErrorMessage="{0} is required")]
[Display(Name="Donation date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DonationDate { get; set; }
The view has an editor for it....
<div class="editor-label">
#Html.LabelFor(model => model.Donation.DonationDate)
</div>
<div class="editor-field">
#Html.TextBox("txtDate", Model.Donation.DonationDate.ToString("dd/MM/yyyy"), new { #class = "date" })
#Html.ValidationMessageFor(model => model.Donation.DonationDate)
</div>
The controller just receives back the model... but when I do this in the controller and give it to another view...
ViewBag.Date = model.Donation.DonationDate;
Every time I just get back
1/1/0001 12:00:00 AM no matter what the date was set to. Any thoughts? Thanks!
Forgot to mention... I'm also using JQuery datepicker on the editor field:
$('.date').attr("placeholder", "dd/mm/yy").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true
});
You can use TextBoxFor so that the view engine knows how to label the form field appropriately (so that the model binder will recognize it on postback):
#Html.TextBoxFor(model => model.Donation.DonationDate, new { #class = "date" })
Alternatively, you could name the textbox correctly manually. I'm not sure exactly what that would look like ...
Update
Ok, I as curious so I checked. The naming convention for nested fields uses the dot notation. So you should be able to write this:
#Html.TextBox("Donation.DonationDate", Model.Donation.DonationDate.ToString("dd/MM/yyyy"), new { #class = "date" })
Update #2
To format the correctly, apply an attribute to the DonationDate property in your model:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
For this to work, you also have to use #Html.EditorFor instead of TextBoxFor.
I am trying to get #String.Format("{0:0.00}",Model.CurrentBalance) into this #Html.TextBoxFor(model => model.CurrentBalance, new { #class = "required numeric", id = "CurrentBalance" })
I just want the currency to show up as .00 inside of my textbox but am having no luck. Any ideas on how I do this?
string.format("{0:c}", Model.CurrentBalance) should give you currency formatting.
OR
#Html.TextBoxFor(model => model.CurrentBalance, new { #class = "required numeric", id = "CurrentBalance", Value=String.Format("{0:C}",Model.CurrentBalance) })
#Html.TextBoxFor(model => model.CurrentBalance, "{0:c}", new { #class = "required numeric", id = "CurrentBalance" })
This lets you set the format and add any extra HTML attributes.
While Dan-o's solution worked, I found an issue with it regarding the use of form-based TempData (see ImportModelStateFromTempData and ExportModelStateToTempData). The solution that worked for me was David Spence's on a related thread.
Specifically:
[DisplayFormat(DataFormatString = "{0:C0}", ApplyFormatInEditMode = true)]
public decimal? Price { get; set; }
Now if you use EditorFor in your view the format specified in the annotation should be applied and your value should be comma separated:
<%= Html.EditorFor(model => model.Price) %>