String.Format for currency on a TextBoxFor - c#

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) %>

Related

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!

Binding lost on #Html.EditorFor when I apply formatting

When using the following I lose the binding on the field
#Html.EditorFor(model => model.Quote.DiscountRate, new { #class = "form-control pull-left " })
And the model field looks like this:
[DisplayFormat(DataFormatString = "{0:P2}",ApplyFormatInEditMode =true)]
public double? DiscountRate { get; set; }
if I remove the DisplayFormat the binding still works.
I also tried the following with the same result:
#Html.TextBoxFor(model => model.Entity.DiscountRate, "{0:P2}", new { #class = "form-control pull-left" })
In both cases if I remove the formatting I get my binding back
What I have discovered is that when you apply a DisplayFormat, it is as the name suggests, for display. If you want to display a decimal value with formatting and make it available for editing, you have to handle the conversion from text back to decimal at post time -- or whenever you need the actual value.

What is a more elegant way to use editorfor for nullable datetime

#if (Model.RecDateFrom.HasValue)
{
#Html.EditorFor(model => model.RecDateFrom,
new {htmlAttributes =
new {#Value = Model.RecDateFrom.Value.ToString("yyyy-MM-dd"),
#class = "form-control input-sm small-input-fix"}})
}
else
{
#Html.EditorFor(model => model.RecDateFrom,
new {htmlAttributes = new {#class = "form-control input-sm small-input-fix"}})
}
#Html.ValidationMessageFor(model => model.RecDateFrom, "", new {#class = "text-danger"})
You can see above how I have to handle if the datetime is null before setting the value. I have to set the value because MVC uses the incorrect format for a date input, making it so chrome doesn't have the correct default value.
I do not want to use the accepted solution in this question because that changes the format of the display for also.
I've tried using editor templates, but it seems like you have to start from scratch, rather than extending the built in editor template for Date datatypes (this seems like a large flaw of MVC, unless I'm missing something).
If you are wanting to render the browsers HTML5 datepicker, you just need to apply the correct attributes to you property. Note the format string must be in the ISO format.
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime RecDateFrom { get; set; }
and then in the view
#Html.EditorFor(m => m.RecDateFrom, new { htmlAttributes = new { #class = "form-control input-sm small-input-fix" } })
Side note: The HTML5 datepicker is not supported in older browsers and not yet at all in FireFox, so it may be better (at least in the short term) to use a jquery plugin (and set the format in the plugin initializer). For example, using the jquery ui datepicker - $('#datepicker').datepicker({ dateFormat: 'dd-mm-yy' })

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.

Formatting TextboxFor content

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))

Categories

Resources