Missing date when i use dot - asp.net-mvc

When i use this code with dot i dont get anything...its blank but when i replace it with slash it works. Can someone tell me what is problem with this?
#{
String date = Model.Edit.BirthDate.ToString("dd'.'MM'.'yyyy.");
}
#Html.Label(date)
#{
String date = Model.Edit.BirthDate.ToString("dd'/'MM'/'yyyy.");
}
#Html.Label(date)
If i use this below i get only year because i didnt put dot at the end of year
#{
String date = Model.Edit.BirthDate.ToString("dd'/'MM'/'yyyy");
}
#Html.Label(date)

Those characters (forward slash, and dot) are not special and can just be input as you want them displayed.
For example:
DateTime.Now.ToString("dd.MM.yyyy") // 22.04.2015
DateTime.Now.ToString("dd/MM/yyyy") // 22/04/2015
In fact, I think the problem is because you are using the wrong overload for Html.Label. The parameter you are supplying is supposed to be an expression that defines which property (from Model) to use. If you want to just display a text value (and not link it to a property) then just use:
#{
String date = Model.Edit.BirthDate.ToString("dd.MM.yyyy");
}
#date
or if you want to render an html label:
<label>#(date)</label>

Related

Display only date and no time in mvc [duplicate]

I have the following razor code that I want to have mm/dd/yyyy date format:
Audit Date: #Html.DisplayFor(Model => Model.AuditDate)
I have tried number of different approaches but none of that approaches works in my situation
my AuditDate is a DateTime? type
I have tried something like this and got this error:
#Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Tried this:
#Html.DisplayFor(Model => Model.AuditDate.ToString("mm/dd/yyyy"))
No overload for method 'ToString' takes 1 arguments
If you use DisplayFor, then you have to either define the format via the DisplayFormat attribute or use a custom display template. (A full list of preset DisplayFormatString's can be found here.)
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }
Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml:
#model DateTime?
#if (Model.HasValue)
{
#Model.Value.ToString("MM/dd/yyyy")
}
That will apply to all DateTimes, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml and the DataType attribute on your property:
[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }
The final option is to not use DisplayFor and instead render the property directly:
#if (Model.AuditDate.HasValue)
{
#Model.AuditDate.Value.ToString("MM/dd/yyyy")
}
I have been using this change in my code :
old code :
<td>
#Html.DisplayFor(modelItem => item.dataakt)
</td>
new :
<td>
#Convert.ToDateTime(item.dataakt).ToString("dd/MM/yyyy")
</td>
If you are simply outputting the value of that model property, you don't need the DisplayFor html helper, just call it directly with the proper string formatting.
Audit Date: #Model.AuditDate.Value.ToString("d")
Should output
Audit Date: 1/21/2015
Lastly, your audit date could be null, so you should do the conditional check before you attempt to format a nullable value.
#if (item.AuditDate!= null) { #Model.AuditDate.Value.ToString("d")}
Googling the error that you are getting provides this answer, which shows that the error is from using the word Model in your Html helpers. For instance, using #Html.DisplayFor(Model=>Model.someProperty). Change these to use something else other than Model, for instance: #Html.DisplayFor(x=>x.someProperty) or change the capital M to a lowercase m in these helpers.
You can use the [DisplayFormat] attribute on your view model as you want to apply this format for the whole project.
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<System.DateTime> Date { get; set; }
#ChrisPratt's answer about the use of Display Template is wrong. The correct code to make it work is:
#model DateTime?
#if (Model.HasValue)
{
#Convert.ToDateTime(Model).ToString("MM/dd/yyyy")
}
That's because .ToString() for Nullable<DateTime> doesn't accept Format parameter.
For me it was enough to use
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime StartDate { set; get; }
I implemented the similar thing this way:
Use TextBoxFor to display date in required format and make the field readonly.
#Html.TextBoxFor(Model => Model.AuditDate, "{0:dd-MMM-yyyy}", new{#class="my-style", #readonly=true})
2. Give zero outline and zero border to TextBox in css.
.my-style {
outline: none;
border: none;
}
And......Its done :)
You could use Convert
<td>#Convert.ToString(string.Format("{0:dd/MM/yyyy}", o.frm_dt))</td>
In View Replace this:
#Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
With:
#if(#Model.AuditDate.Value != null){#Model.AuditDate.Value.ToString("dd/MM/yyyy")}
else {#Html.DisplayFor(Model => Model.AuditDate)}
Explanation: If the AuditDate value is not null then it will format the date to dd/MM/yyyy, otherwise leave it as it is because it has no value.
After some digging and I ended up setting Thread's CurrentCulture value to have CultureInfo("en-US") in the controller’s action method:
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Here are some other options if you want have this setting on every view.
About CurrentCulture property value:
The CultureInfo object that is returned by this property, together
with its associated objects, determine the default format for dates,
times, numbers, currency values, the sorting order of text, casing
conventions, and string comparisons.
Source: MSDN CurrentCulture
Note: The previous CurrentCulture property setting is probably optional if the controller is already running with CultureInfo("en-US") or similar where the date format is "MM/dd/yyyy".
After setting the CurrentCulture property, add code block to convert the date to "M/d/yyyy" format in the view:
#{ //code block
var shortDateLocalFormat = "";
if (Model.AuditDate.HasValue) {
shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("M/d/yyyy");
//alternative way below
//shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("d");
}
}
#shortDateLocalFormat
Above the #shortDateLocalFormat variable is formatted with ToString("M/d/yyyy") works. If ToString("MM/dd/yyyy") is used, like I did first then you end up having leading zero issue. Also like recommended by Tommy ToString("d") works as well. Actually "d" stands for “Short date pattern” and can be used with different culture/language formats too.
I guess the code block from above can also be substituted with some cool helper method or similar.
For example
#helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("M/d/yyyy");
}
#shortDateLocalFormat
}
can be used with this helper call
#DateFormatter(Model.AuditDate)
Update, I found out that there’s alternative way of doing the same thing when DateTime.ToString(String, IFormatProvider) method is used. When this method is used then there’s no need to use Thread’s CurrentCulture property. The CultureInfo("en-US") is passed as second argument --> IFormatProvider to DateTime.ToString(String, IFormatProvider) method.
Modified helper method:
#helper DateFormatter(object date)
{
var shortDateLocalFormat = "";
if (date != null) {
shortDateLocalFormat = ((DateTime)date).ToString("d", new System.Globalization.CultureInfo("en-US"));
}
#shortDateLocalFormat
}
.NET Fiddle
Maybe try simply
#(Model.AuditDate.HasValue ? Model.AuditDate.ToString("mm/dd/yyyy") : String.Empty)
also you can use many type of string format like
.ToString("dd MMM, yyyy")
.ToString("d") etc
This is the best way to get a simple date string :
#DateTime.Parse(Html.DisplayFor(Model => Model.AuditDate).ToString()).ToShortDateString()
Instead of
#Html.DisplayFor(Model => Model.AuditDate)
Use
#Model.AuditDate.ToString("MM/dd/yyyy")
This style renders the date as: 06/02/2022.
You can style your string accordingly to how you need it.
I had a similar issue on my controller and here is what worked for me:
model.DateSigned.HasValue ? model.DateSigned.Value.ToString("MM/dd/yyyy") : ""
"DateSigned" is the value from my model
The line reads, if the model value has a value then format the value, otherwise show nothing.
Hope that helps
You can use this instead of using #html.DisplayFor().
#Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.AuditDate))
You just need To set Data Annotation in your Model.
[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime AuditDate {get; set;}
On view(cshtml page)
#Html.DisplayFor(model => model.AuditDate)
Nothing else you need to do.
Hope its useful.
See this answer about the No overload for method 'ToString' takes 1 arguments error.
You cannot format a nullable DateTime - you have to use the DateTime.Value property.
#Model.AuditDate.HasValue ? Model.AuditDate.Value.ToString("mm/dd/yyyy") : string.Empty
Tip: It is always helpful to work this stuff out in a standard class with intellisense before putting it into a view. In this case, you would get a compile error which would be easy to spot in a class.

How to best implement something like shortcodes in Grails

How can I best implement something like shortcodes (thats what it's called in Wordpress) in Grails.
I have a Grails application where the user can input text. This text is saved in the Database. The Text should contain something like "shortcodes":
class Page(){
String text = "please display [form A] above here."
}
In my view I display the value text from my domain Object.
${domainObject.text}
eg: "[form A]" should display a referenced Form A in the position where it was put in the text.
What's the best way I can do this in Grails.
Best approach is to use SimpleTemplateEngine. Using this you could have standard ${} block to specify variables.
Use method like below:
String renderTemplate(Reader template, Map bindings) {
try {
def engine = new groovy.text.SimpleTemplateEngine()
return engine.createTemplate(template).make(bindings)
} catch (MissingPropertyException mpe) {
log.error("Missing property in template binding", mpe)
}
return ""
}
Example:
String text = "please display ${formA} above here."
String parsedText = renderTemplate(new StringReader(text),[formA:'http://www.yourlink.com'])
Hope it helps!!

How to capitalize each word in a string using Swift iOS

Is there a function to capitalize each word in a string or is this a manual process?
For e.g. "bob is tall"
And I would like "Bob Is Tall"
Surely there is something and none of the Swift IOS answers I have found seemed to cover this.
Are you looking for capitalizedString
Discussion
A string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
and/or capitalizedStringWithLocale(_:)
Returns a capitalized representation of the receiver using the specified locale.
For strings presented to users, pass the current locale ([NSLocale currentLocale]). To use the system locale, pass nil.
Swift 3:
var lowercased = "hello there"
var stringCapitalized = lowercased.capitalized
//prints: "Hello There"
Since iOS 9 a localised capitalization function is available as capitalised letters may differ in languages.
if #available(iOS 9.0, *) {
"istanbul".localizedCapitalizedString
// In Turkish: "İstanbul"
}
An example of the answer provided above.
var sentenceToCap = "this is a sentence."
println(sentenceToCap.capitalizedStringWithLocale(NSLocale.currentLocale()) )
End result is a string "This Is A Sentence"
For Swift 3 it has been changed to capitalized .
Discussion
This property performs the canonical (non-localized) mapping. It is suitable for programming operations that require stable results not depending on the current locale.
A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators (listed under getLineStart(_:end:contentsEnd:for:)). Some common word delimiting punctuation isn’t considered, so this property may not generally produce the desired results for multiword strings.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercased for an example.
There is a built in function for that
nameOfString.capitalizedString
This will capitalize every word of string. To capitalize only the first letter you can use:
nameOfString.replaceRange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalizedString)
Older Thread
Here is what I came up with that seems to work but I am open to anything that is better.
func firstCharacterUpperCase(sentenceToCap:String) -> String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = sentenceToCap.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
or if I want to use this as an extension of the string class.
extension String {
var capitalizeEachWord:String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = self.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
}
Again, anything better is welcome.
Swift 5 version of Christopher Wade's answer
let str = "my string"
let result = str.capitalized(with: NSLocale.current)
print(result) // prints My String

Only first parameter value is getting while calling controller method using Url.action.

I am calling a controller method using Url.action like,
location.href = '#Url.Action("Display", "Customer", new { username = "abc",name = "abcdef",country = "India",email = "abc#hmail.com",phone = "9456974545"})';
My controller method is,
public void Display(string username, string name, string country, string email, string phone)
{ }
In this method, I can get only the value of first parameter (username). Its not getting other parameter values that is passed. All other values are null.
Please suggest me, whats wrong?
By default every content (which is not IHtmlString) emitted using a # block is automatically HTML encoded by Razor.
So, #Url.Action() is also get encoded and you are getting plain text. And & is encoded as &
If you dont want to Encode then you should use #Html.Raw(#Url.Action("","")).
The answer for you question is :
location.href = '#Html.Raw(#Url.Action("Display", "Customer", new { username = "abc",name = "abcdef",country = "India",email = "abc#hmail.com",phone = "9456974545"}))';
Hope this helps
There is a problem with '&' being encoded to the '& amp;'
model binder doesnt recognise this value. You need to prevent this encoding by rendering link with Html.Raw function.
Use '#Html.Raw(Url.Action......)'

Numeric Format for No Thousands Separator

Is there a number format that would produce a localized number without the thousands separator?
Globalize.format("1000.12", "n?" )
I realize I could do:
Globalize.culture().numberFormat[","]="";
But I have some fields where I want it off and some where it should be on. For example... If the value is:
1000.123 -> Want it to show formatted to 1000,12 or 1000.12 depending on locale..But without the thousands separator.
You can use the "d" format instead of the "n" format to exclude the thousands separator.
Globalize.format(1000.12, "d");
Edit
Note that this will only work if you don't care about the decimal part.
If you care about the decimal part, as far as I know, you can't exclude the thousands separator except through one of the following methods:
Set the thousands character in the culture object to an empty string:
Globalize.culture().numberFormat[","] = "";
Globalize.format(1000.12, "n");
You could turn this into a utility function fairly easily:
function formatNumberNoThousands(num, format, culture) {
var numberFormat = Globalize.cultures[culture || Globalize.culture().name].numberFormat,
thousands = numberFormat[","];
numberFormat[","] = "";
try { return Globalize.format(num, format, culture); }
finally { numberFormat[","] = thousands; }
}
Perform a replace on the string result of the format:
Globalize.format(1000.12, "d").replace(new RegExp("\\" + Globalize.culture().numberFormat[","], "g"), "");
Which can also be easily turned into a utility function:
function formatNumberNoThousands(num, format, culture) {
return Globalize.format(num, format).replace(new RegExp("\\" + Globalize.culture(culture).numberFormat[","], "g"), "");
}
With this approach, if you know there will never be more than one thousands character in the formatted result you can remove the regexp. Otherwise if you plan on using this a lot or inside of a loop, you will want to cache the regexp and re-use it.

Resources