What's the proper way to check in Razor if ViewBag has a value set? I know that I can do
if(ViewBag.Foo != null) {
...
}
But looking in the events stream in VS 2015 I notice this generates a (handled) RuntimeBinderException.
The fact that this throws an error leads me to suspect that this is not the correct way to check the presence of a value, and is actually harming performance (though I have not done any testing). In addition it doesn't help you distinguish between a value being absent and the value being set to null.
Is there a more correct approach?
There is no way defined by razor developers, however you can see this to do it by yourself using extension method.
Related
I found a very strange behavior in our grails application today that i want to share with you.
We are using grails 2.3.11 on mysql 5.1.48.
We had a DomainObject.findById( id ) in one of your Controller actions.
We failed to check the id for a null value so DomainObject.findById( null )
would be called when no id is passed as an argument.
Normally DomainObject.findById( null )
will return null but there is a special condition that will yield other results!
If the controller action called before that inserted a new record in the database (lets call it Object B), regardless of the domain object stored, the DomainObject.findById( null ) will find the DomainObject with the same Id the Object B got on insert.
So when the controller action called before saved anything the findById(null) will return a row. And that row will have the same id the last inserted element got.
I am totally aware that using findById(null) is not the desired way to do it but I was quite shocked about the results it yielded. But returning any seemingly "random" result seems very strange to me.
I also want to note that DomainObject.get(null) will not suffer from this problem.
Anybody else witnessed this?
There is an active Jira pointing in this direction: https://jira.grails.org/browse/GRAILS-9628 but its not really describing this issue.
We don't really support passing null as an argument to a dynamic finder like that. Dynamic finders have explicit support for querying by null. Instead of DomainClass.findByName(null) you would call DomainClass.findByNameIsNull(). If you have a reference that may or may not be null, instead of passing that as an argument to a dynamic finder, the code can almost always be made cleaner by writing a criteria query or a "where" query that has a conditional in it.
I hope that helps.
Thx for your information scot.
I have further details. This behaviour is also altered by the underlying database.
While mysql suffers from this, maria-db (a mysql clone) does not!
So what happens is bound to the underlying database system.
That should not happen to an abstraction layer ....
I have an app that relies on a web service that I have no control over. I'm currently trying to solve a bug.
In a particular case, an asynchronous HTTP request returns
"<null>"
When this happens I get an exception and my app crashes.
I've tried every method I can think of to test for this in an if statement including comparing various strings, arrays, and testing for the characters < and >. Essentially I want to break from a method if the value is found.
Has anyone run into this before, and how did you solve it?
Many thanks :)
Have you tried using the below code to test for it
if (myObject == [NSNull null]) {
// handle it
} else {
//
}
"The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary)." - Apple
Ok, I figured it out. It must have helped to write the problem down. I hadn't created an IDENTICAL null object to compare it to yet. My null object actually was generated by a snippet of JSON code, so all i had to do was replicate such an object and use isEqual: to compare them.
I am using SWFAddress in actionscript 3 to control urls for navigation and controls, and while I am able to target and change specific parameters, I feel like I am missing a cleaner and more consistent way of handling it, perhaps even a feature or method I am not aware of.
Say I have a url and I want to change just the second param of def to xyz.
http://localhost/some-page/#/?param1=abc¶m2=def¶m3=ghi changed to
http://localhost/some-page/#/?param1=abc¶m2=xyz¶m3=ghi
I currently am doing:
if (SWFAddress.getParameterNames().indexOf("param2") >= 0) {
SWFAddress.setValue(SWFAddress.getPath() + "?"
+ SWFAddress.getQueryString().replace("param2=" + SWFAddress.getParameter("param2"), "param2=xyz"))
Essentially, checking if the param exists, checking what its current value is, then recreating the whole url using base, '?", and query, making sure I replace the the parameter and the parameter's value, making sure I don't miss the equal sign. This get's sloppy, and is error prone if the param exists but is not set to anything, or whether or not there is an equal sign, and a host of other pitfalls.
So, I can not just tell SWFAddress to update that one parameter in the url? A theoretical function of SWFAddress.setParam("param2, "xyz").
Has anyone coded their own method to micro-manipulate SWFAddress and the url, beyond the single function they supply you with of setValue(val:String)?
I think the short answer is no. According to the documentation there is no setParameter to go with the getParameter method. Looking at the code, it seems that the URL is not cached as a property in the class and therefore cannot be manipulated other than via the setValue method which, of course, updates the URL in the browser.
Presumably you're already parsing the URL in your onChange event so you can use the values to set your application state? If so, you shouldn't need to do so again when you come to rebuild the URL prior to updating it from Flash. If you store the deep-link properties on a Model class somewhere you can handle the defaulting, updating, and error checking without needing to resort to String manipulation. You would then rebuild the URL using those properties, a process you could abstract into a method in your Model class if required.
You should also note that the following line is not particularly robust since it will return true for properties such as param22 and sparam2:
if (SWFAddress.getParameterNames().indexOf("param2") >= 0) { }
I'm new to grails, but have previous experience using .net with c# and linq to query databases.
I'm trying to filter a list of objects by optional items using a multiple selection drop box. So to the controller I will get a list of parameters some of which will be null. So I want to have something akin to
DailyProduction.Where(x => loaction.contains(x.location)).Select().ToList().
However, it doesn't see quite as simple with in groovy and grails.
Here is what I've tried:
def filteredList = DailyProductionReport.createCriteria()
def results = filteredList.list {
if(params.locationSelect != null)
'in'("location", [params.locationSelect.each{ it != null}])
}
But I get a Runtime Exception that says:
Class:
java.lang.ClassCastException
Message:
[Ljava.lang.String; cannot be cast to java.lang.String
I've tried look over different forums with out any luck. I'm almost at my wits end. If any groovy master can shed some light on things for me I'd greatly appreciate it.
Thanks
It looks like your problem might be
[params.locationSelect.each{ it != null }]
each is used for iteration and the resulting expression is just the list being iterated over. Also, the square brackets nest that list in another list. You probably want
'in'('location', params.locationSelect.findAll { it != null })
In this particular case, you can also just use the identity closure since "groovy truth" for objects is the same as testing for null:
'in'('location', params.locationSelect.findAll())
Using Struts 2.1.6, xwork 2.1.2 and ognl 2.6.11
In my struts action I have a Map that I am fetching elements from using OGNL. If the key I am using to fetch with does not exist in the map then OGNL returns an empty object array, that OGNL converts to a string and I get the object reference java.lang.Object#6.... This occurs in several places and seems to be the the map having the value generic specified as an Object. This is not something I can change.
I have traced the problem for a while, but when I ended up deep into the guts of the OGNL code and I did not see a light at the end of the tunnel. Currently I am going to go with an ugly hack of checking the string return to see if it starts with "java.lang.Object#" and if so return an empty string. I don't like the solution but thats what time permits.
Has anyone encountered a similar problem?
Also, where did OpenSymphony go? updates to their webiste appear to have dried up, the user forums say they are being converted to Google Groups no later than Nov-12-09
This is a problem with null values: if value is null, default behavior is to create a value using default constructor. Since the value type of your map is Object, new Objects are created where null is.
In order to stop this behavior:
use #CreateIfNull( value = false )
use mapName_CreateIfNull=false in classname-convertion.properties file.