Formatting TextboxFor content - c#

I have this :
#Html.TextBoxFor(m => m.MyClass.MyValue, new { style = "width: 138px", id = "mTextBox", maxlength = 10 })
I'd like format the content. Where can I do this ?
Thanks,

This worked for me..
#Html.TextBoxFor(model => model.INVOICE_DATE,"{0:MM/dd/yyyy}", new { maxlength = 10, style = "min-height:30px; min-height: 30px; border-color: green; " })

You can Use
Html.TextBox("MyValue",String.Format('<your format>',Model.MyClass.MyValue))
for example "{0:d}" or "{0:c}"
or if you want to use only Html.TextBoxFor then u can format your content from model.

I've used EditorFor in a case such as this and decorated my property with DisplayFormat attribute
in my view:
<%: Html.EditorFor(model => model.StartDate)%>
and on my view model
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime StartDate { get; set; }

You can also do it, setting only the format string:
TimeSpan Format Strings
#Html.TextBoxFor(model => model.Fecha, "{0:G}", new { #class="vld-required" })

for example to display the TimeStamp in ShortDate+ShortTime ("3/9/2010 4:15 PM")
Html.TextBoxFor(model => model.MyClass.TimeStamp, String.Format("{0:g}",Model.MyClass.TimeStamp))

Related

MVC EditorFor Timespan is removing the seconds

The editor generated for my Timespan only includes hours and minutes. I would like it to be standard, i.e. hh:mm:ss.
I would have thought the default would be that, which I've tried. I've also tried
[DisplayName("Start Time")]
[DisplayFormat(DataFormatString = "{0:hh\\:mm\\:ss}", ApplyFormatInEditMode = true)]
[DataType(DataType.Time)]
public TimeSpan? StartTime { get; set; }
The view
<div class="form-group">
#Html.EditorFor(model => model.SearchCriteria.StartTime, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.SearchCriteria.StartTime, "", new {#class = "text-danger"})
</div>
You can use inputmask to get the masking/formatting effect:
Add class to your control you want to format e.g. time-mask
#Html.EditorFor(model => model.SearchCriteria.StartTime, new {htmlAttributes = new {#class = "form-control time-mask"}})
Add reference to jquery.inputmask.bundle package
Use the inputmask function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.time-mask').inputmask("hh:mm:ss", {
placeholder: "hh:mm:ss",
showMaskOnHover: false
});
});
</script>
Just keep in mind that TimeSpan not designed to represent time of day, but it is for showing a duration of period so it is normal to have TimeSpan value in negative or longer than 24 hours.
Update:
The behavior is normal since [DataType(DataType.Time)] annotation will add type="time" to the input element in your HTML which is a HTML5 attribute used by some of the browsers like Chrome but not FireFox for example. If you want to use the annotation then you need to add an attribute step="1" to the EditorFor so your code will be:
#Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { #class = "form-control", #step = "1" } }).
Note this will work on Chrome but not on FireFox, IE 11 and earlier versions.That's why I suggested the other solution.

Excluding time from TextBoxFor when ViewModel setup as DataType of Date

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!

Set a view's textbox (datetime field) to display readonly current datetime

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.

My date doesn't seem to be posting back in the form to the controller

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.

String.Format for currency on a 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) %>

Categories

Resources