How to use Humanize inside #Html,DisplayFor() - asp.net

How can I display Date Humanizely inside DisplayFor?
I tried like this : #Html.DisplayFor(model =>model.EndDate.Humanize())
but editor shows error like:
an expression tree may not contain a call or invocation that uses
optional arguments

Html.DisplayFor is a templated helper, which just means it returns the value of the model expression using a template. The default template is simply calling ToString() on the property referenced by the model expression. As such, what you pass into it must be a model expression referencing a particular property; you cannot do something like call Humanize on it.
However, you can define your own template. This entails creating a view in Views\Shared\DisplayTemplates, which conforms to one of these naming conventions:
It's named after the type it should be used for, e.g. DateTime.cshtml will be applied to any property that is of type DateTime.
It's named after one of the members of the DataType enum, in which case, it's utilized when that DataType is applied to a particular property, e.g. Date.cshtml will be utilized when you apply the attribute [DataType(DataType.Date)].
It's named whatever you like, but that name is explicitly specified for the property using the UIHint attribute, e.g. if you apply an attribute like [UIHint("MyAwesomeDateTime")] and associated MyAwesomeDateTime.cshtml view will be used.
As such, if you were to create a view like Views\Shared\DisplayTemplates\DateTime.cshtml with the contents:
#model DateTime
#Model.Humanize()
Then, simply calling #Html.DisplayFor(m => m.EndDate) will return the humanized date you're looking for. Since EndDate is a DateTime, DisplayFor will utilize your DateTime.cshtml template, which outputs the model (your DateTime with Humanized chained.
An alternative way to specify a display template is to pass it in directly. This is useful when you have a one-off situation and you don't want the template to apply to everything of a particular type. For example, if you just wanted EndDate humanized, but other dates to display as normal, that could be achieved by doing something like:
#Html.DisplayFor(m => m.EndDate, "HumanizedDate")
You would then of course need an associated HumanizedDate.cshtml. You can also employ UIHint on your property as described above here, if you'd prefer to keep this out of the view, and on your model instead.
All that said, display templates are best utilized when there's complex constructions involved. As Stephen pointed out in the comments below your question, you could easily just do: #Model.EndDate.Humanize(), which not only is more terse and explicit than #Html.DisplayFor(m => m.EndDate), but also doesn't require adding custom views or attributes to your model properties.

Related

Graphql Schema doku displays Input type automatically with Input

I have added leangen/graphql-spqr as described in the readme.
Before we had a custom implementation of graphql types like in customtype.types.gql.
After implementation, everything works fine, except the type which are called e.g. OperatorInput, are named in the autogenerated graphql doc like "OperatorInputInput".
I tried to Change it like this in the declaration:
#GraphQLArgument(name = "OperatorInput", description = "Required fields for Operator") OperatorInput operator
But it wasn't applied.
Do you know any workaround?
This is intended. Keep in mind that in GraphQL's type system, input and output types are strictly different. Let's say you have this in Java:
public Book saveBook(Book in) {...}
The Book that is the return type and the Book that is the argument type are 2 different types in GraphQL, and must have unique names. So Input is added automatically to make the names unique.
If you're 100% sure you want to override this, register a custom TypeInfoGenerator via GraphQLSchemaGenerator#withTypeInfoGenerator. You can inherit from DefaultTypeInfoGenerator and override generateInputTypeName. BUT! Do pay attention that if you end up producing the same name for 2 different types, all hell breaks loose. So maybe only drop the suffix Input if the classname already ends with Input and never ever use such classes for output.
Btw #GraphQLArgument sets the name of the argument, not the name of the type of the argument.

Complex type checks in XQuery

I have a schema that has many complexType, some of which have subtypes (via xsi:type). I need to create an XQuery expression that checks that an element (MyPath) is a member of a parent type, but no others, I've tried an expression in the form below with no luck.
/MyPath[element(*,ParentClass) and not element(*,ChildClass)]
It appears element applies to all the children in the context it is called, but not itself (MyPath), which yields no results.
I also tried the instance of operator, but this appears to only work for simpleType.
You should use
. instance of element(*, ParentClass)
and not(. instance of element(*, ChildClass))
If this doesn't work please supply an MCVE
An alternative, using Saxon extension functions, is to test the type annotation directly: saxon:type-annotation(.) eq xs:QName('ParentClass')
Of course, there's a question about whether this is good practice. The whole point of defining a derived type is that it is supposed to be substitutable for the base type; everywhere you can use an instance of the parent type, you should be able to substitute an instance of the child type. You appear to be deliberately trying to contrive a query in which this is not the case.

Adding a callback when reading from an object in Twig

Let's say I have a basic entity called Entity which is mapped to a database table. This entity has got two properties: propertyA and propertyB.
One particularity of this entity is, although we may store whatever we want in these properties, when using the value of propertyB on a Twig template with entity.propertyB we want to systematically truncate the value to 100 characters.
Now, this is perfectly doable in several ways:
Truncate the value directly in the getPropertyB() method;
Register a Twig extension and create a dedicated filter;
Add a lifecycle callback on the entity to truncate the value before the object is actually created.
As this is strictly a display rule, and not a business rule on our entity, the second solution seems to be the best IMHO. However, it demands we apply the filter every time we need to use the value of propertyB in a template. Should an unaware developer come by, the value may not be truncated.
So my question is: is there a way to register some kind of callback, strictly restricted to the view model wrapping our entity, which would allow us to apply some filters on the fly on some of its properties ?
Since you never need to access anything beyond 100 characters, you can truncate the property in its setter. This doesn't really pollute Entity code, because this is some logic inherent to it.

Asp.NET MVC Model Binding Not Picking Up A Value for List Item

I've got an object with a list defined inside it which points to a type that can be inherited. From what I understand MVC's default model binder will always instance the base type when reading data back in to this array from a form so by default I will have a list of base types.
So I need to use my own model binder and override CreateModel to instance a specific type (say from a hidden field). However when I do this and use
bindingContext.ValueProvider.GetValue("ModelType")
it always returns null even though through using fiddler I can see that form value Settings[0].ModelType contains my objects type and I need this value in CreateModel to instance the correct type.
Solved it. If your array objects need to be typed based on each item you need to use the following call to get "into" the array item
bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ModelType")
I'm not sure if this is the standard way to do it. If anyone has any better suggestions feel free to add them

ASP.NET Razor Model syntax in the view

a few newbie questions here:
In a strongly typed view, why:
#model MyProj.Models.User
Why do we use lambdas: ? What exactly does that do? Why not just model.Email?
1. #Html.DisplayNameFor(model => model.Email)
Why doesn't this work? Didn't we call the variable model? (I know I should use #html.() but why isn't model recognisable?
2. users name is: #model.Name
Why does it work with an uppercase 'M'? Didnt we name it with a lower case?
3. users name is: Model.Name
Thanks!
Why do we use lambdas: ? What exactly does that do? Why not just
model.Email?
The DisplayNameFor as well as all the other *For helper methods are taking advantage of the ability of lambda expressions to participate in Expression Trees.
By itself this lambda expression is simply taking in a model type and returning a String. But there is more information needed to get the display name.
In pseudo code, that method is doing:
1.) Treat the lambda as an Expression
2.) Parse the expression to get the name of the property
3.) Use reflection to get the DisplayNameAttribute for that property
4.) Extract the value if it exists, otherwise use the name of the property
5.) Generate a label for that property using either the display name, or property name
Without using Expression trees, you would end up having to pass the property name in as a string... and that just sucks. This provides a strongly typed way of using reflection without magic strings.
Why doesn't this work? Didn't we call the variable model? (I know I
should use #html.() but why isn't model recognisable?
#model is a special directive that is treated differently by Razor. It's like a reserved keyword that isn't any different than class or int.
Why does it work with an uppercase 'M'? Didnt we name it with a lower
case?
Model is a property on your view that has the type you defined using the #model directive, and references your model. Without using the #model directive it would have a type of dynamic.

Resources