0

I'm refactoring my code and moving business logic from the controller to the model, but it seems that Json functionalities are not available in the model. It is so strange that I'm sure it's me that I'm missing something.

In the controller I can do

var myList = (from myItem in db.MyModel
              where (myItem.code == "somecode") 
              select myItem);
JsonResult jList = Json(myList);

As I move this code into the model I have an error on line

JsonResult jList = Json(myList);

saying that "The name 'Json' does not exist in the current context.

I have the same using statements in both model and controller, (System.Web.Mvc should be the one for Json functionality) and by right clicking Json i do not have the "resolve" option.

What am I missing?

3 Answers 3

1

As was pointed out the Json(myList) call you're making is to a method on the base controller class. As you're no longer executing that code in a class that derives from Controller the method is no longer available.

However, that method is just a convenience wrapper around the creation of a JsonResult. To replicate the functionality outside of a controller you can use:

JsonResult jsonResult = new JsonResult()
{
    Data = data,
    JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
return jsonResult;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it is exactely what I needed.
1

In this case Json() is the method of Controller base class.

You can try using JSON.Net, or some other serialilzer.

2 Comments

Thanks for the suggestion, anyway I prefer to go with Craig W, this way I do not need to link another library.
If you don't want to add another library, you can use built-in JavaScriptSerializer class: msdn.microsoft.com/en-us/library/… My understanding is that's what's used for JsonResult.
0

Make sure your controller inherits from the Controller abstract class. This code snippet is from my base api controller but it will be the same theory (ApiController => Controller)

public class BaseApiController : ApiController
{
    public Code.CodeService CodeService { get; set; }

    /// <summary>
    /// Constructs the Base Controller and sets up the global properties that need to  be accessible by other Controllers.
    /// </summary>
    public BaseApiController()
    {
        CodeService = new Code.CodeService();
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.