asp.net mvc 5 - How do I return a ViewModel from a Web API controller method AS JSON? -


my controller method called , view model loads data, throws error upon returning.

public accountmanagerviewmodel get(string id) {     accountmanagerviewmodel account = new accountmanagerviewmodel(guid.parse(id));      return account; } 

i tried adding [serializable] attribute class no luck.

does i'm doing make sense? we're hoping reuse code our mvc app in new web api app don't want have create new classes have manually populate our viewmodels , return web api controller methods.

you need see error is. maybe guid incorrect? incorrect format or not exit?

that should work fine. 1 thing keep in mind not serialise complex models, recursion,etc. may error may getting. (but can disable recursion serialisation too)

the best way check error is, open developer console in chrome/ firefox , enable xmlhttprequest logging. in console can click on red response , view error asp.net.

enter image description here

another way check code getting hit, put breakpoint on first line of code expecting hit , run client. can step through lines , see error is.

you can turn of deep serliastion entity framework models.

var json = globalconfiguration.configuration.formatters.jsonformatter; json.serializersettings.preservereferenceshandling =      newtonsoft.json.preservereferenceshandling.none; 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -