-1

I'm new in asp.net mvc and want to return json with web api controller,for that purpose write this code:

public JsonResult Get()
        {
            var users = GetUsers();
            return Json(users, JsonRequestBehavior.AllowGet);
        }
        private List<TestModel> GetUsers()
        {
            var usersList = new List<TestModel>
            {
                new TestModel
                {
                    id = "1",
                    name = "behzad"
                }
            };
            return usersList;
        }


but int this line:

JsonRequestBehavior.AllowGet


get this error:

Severity Code Description Project File Line Suppression State Error CS1503 Argument 2: cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings' WebApplication1 D:\behzad\project\aspweb api\WebApplication1\WebApplication1\Controllers\HelloController.cs 17 Active

5
  • 1
    Who down vote me?I'm say beginner! Commented May 25, 2017 at 8:47
  • return Json(new SelectList(users.ToArray(), "id", "name"), JsonRequestBehavior.AllowGet); Try this it will work Commented May 25, 2017 at 8:51
  • @LaxmanGite get that error my friend Commented May 25, 2017 at 8:53
  • var statelist = _masterService.GetStates().Where(st => st.CountryId == Id).ToList(); return Json(new SelectList(statelist.ToArray(), "Id", "Name"), JsonRequestBehavior.AllowGet); make your code like this Commented May 25, 2017 at 8:54
  • Possible duplicate of JSON return error with ASP Commented May 25, 2017 at 8:56

2 Answers 2

2

If you want to all your ASP.Net Web API result return JSON. you need a global configuration to make your action comfortable.

for this case, you don't need to call any extra service to resolve JSON. follow this:

    public List<TestModel> Get()
    {
        return GetUsers();
    }

but you need some setting to have it, put below line to the Global.asax file and Application_Start method:

GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
Sign up to request clarification or add additional context in comments.

Comments

0
public IHttpActionResult Get()
{
        var users = GetUsers();            
        return Ok(users);
}
private List<TestModel> GetUsers()
{
        var usersList = new List<TestModel>
        {
            new TestModel
            {
                id = "1",
                name = "behzad"
            }
        };
        return usersList;
 }

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.