-1

In my models constructor I want to be able to use:

string s = Json(object);

The only way I can get Json() to work is if I make the model class inherit Controller.

I don't know enough to know if this is a bad thing but it strikes me as a warning that the model shouldnt be inheriting from controller. Is this bad practice to use Json() inside model? Is this putting too much logic inside a model?

If it matters is there another way to add reference to get Json() to work without inheriting controller?

Guerrilla
  • 13,375
  • 31
  • 109
  • 210
  • Well, a model is not a controller, so I would say it should not inherit from it. Have you figured out _why_ inheriting from `Controller` allows you to use the `Json` method? – D Stanley Nov 06 '14 at 16:31
  • 4
    That won't work at all. `Json()` returns an `ActionResult`. – SLaks Nov 06 '14 at 16:31
  • why do you need to do this? – Marian Ban Nov 06 '14 at 16:31
  • https://www.google.com/search?q=c%23+json+serializer – SLaks Nov 06 '14 at 16:32
  • Why do you want to create a `JsonResult` from a model? – D Stanley Nov 06 '14 at 16:32
  • I want to store a Json string based on an object. MVC 5 has Json.net installed by default and on their site I can see a JsonConvert() method but I cannot find a reference to get this method working (ctrl + . isnt showing anything) – Guerrilla Nov 06 '14 at 16:36
  • @Guerilla, what do you intend to do with that json string after you've obtained it? Are you not returning it to the client? – Kirk Woll Nov 06 '14 at 16:37
  • @Kirk yes and also saving to database, I guess I was just thinking to have it in Json format in the model to make it easier but the more I think about it the sillier it sounds, I should just store object in model and serialize when its needed in controller. Sorry – Guerrilla Nov 06 '14 at 16:42
  • @Guerrilla, yes, you've hit upon the idiomatic approach. – Kirk Woll Nov 06 '14 at 16:43
  • "using Newtonsoft.Json;" was what I was looking for. Sorry again. – Guerrilla Nov 06 '14 at 16:45

1 Answers1

2

Absolutely not, you should not inherit Model from Controller.

ASP.Net MVC models are often just data transfer objects with minimal logic - Yes or no: Should models in MVC contain application logic?. There are other views too [MVC: Where to put business logic?, but there is no case where you would make "model" to be a Controller.

Note: You may be looking for Parse JSON in C#, not using Controller.Json that returns ActionResult.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179