Samantha J T Star
Samantha J T Star

Reputation: 32838

How can I return a JSON object from ASP.Net WebAPI?

I want to return something like this but it doesn't work:

if (user == null)
{
    return Ok({name: true});
}
return Ok({name: false);

Can someone tell me how I can make it return a value of true of false for a element "name" from my action method.

Upvotes: 1

Views: 66

Answers (1)

Bruno Pessanha
Bruno Pessanha

Reputation: 3024

If you are using Web API, create a class to have your property Name:

public class NameResponse {
    public bool Name { get; set; }
}

And return the JSON like this:

Request.CreateResponse<NameResponse>(HttpStatusCode.OK, new NameResponse() { Name = true });

If you're not using Web API and using a normal Controller you need to do this:

if (user == null)
{
    return Json(new { name = true });
}
return Json(new { name = false });

Upvotes: 2

Related Questions