Strongly type returned JSON using MonoRail
-
16-09-2019 - |
Question
I am calling the following method in my controller using $.getJSON()
[return: JSONReturnBinder]
public object ProfileFields()
{
var userfields = _profileSvc.GetFields(282);
var fields = from f in userfields
select new {f.ID, f.FieldName};
return fields;
}
My _profileSvc comes back with extra data that I don't need (actually I get NHibernate errors because the session is closed).
Is there a better way to do what I am doing? Should I strongly type the data I am returning or is this approach sufficient?
Thanks.
Solution
I would use a projection (SetProjection()
) and SetResultTransformer()
to strongly-type the result to a DTO.
See:
- http://www.nhforge.org/doc/nh/en/index.html#querycriteria-projection
- http://www.junasoftware.com/blog/nhibernate-setresulttransformer-and-dto.aspx
- http://ayende.com/Blog/archive/2007/08/30/Slicing-amp-Dicing-Queries-with-NHibernate.aspx
- http://devlicio.us/blogs/derik_whittaker/archive/2009/05/27/nhibernate-amp-setprojects-setprojects-w-list-gotcha.aspx
OTHER TIPS
Have you already tried using
[return: JSONReturnBinder(Properties = "ID,FieldName")]
public object ProfileFields()
{
var userfields = _profileSvc.GetFields(282);
return userfields;
}
I hope this helps.
First, I would change the return value of the action to be an IList...
I think that the session closed error may stem from a delayed-execution of 'var fields'. If you change your return statement to fields.ToList(), that will force the execution of the lambda expression and you might get rid of the Session error:
[return: JSONReturnBinder]
public object ProfileFields()
{
var userfields = _profileSvc.GetFields(282);
var fields = from f in userfields
select new {f.ID, f.FieldName};
return fields.ToList();
}