Returning result as JSON instead of HTML - html

I am calling and displaying a java web service using ASP.NET Web API. How do i make it such that when i run my ASP.NET Web API, the page shows JSON data instead of HTML?
Here are my codes:
DemoRestfulClient.cs
public class DemoRestfulClient
{
private string BASE_URL = "http://localhost:8080/";
public Task<string> AdditionJava2()
{
{
try
{
var client = new HttpClient();
client.BaseAddress = new Uri(BASE_URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("AdditionJava2").Result;
return response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
HttpContext.Current.Server.Transfer("ErrorPage.html");
}
return null;
}
}
}
DemoController.cs
public class DemoController : Controller
{
private DemoRestfulClient demoRestfulClient = new DemoRestfulClient();
public ActionResult Index()
{
var Result1 = demoRestfulClient.AdditionJava2().Result;
return Content(Result1);
}
}
Someone please help me. Thank you so much in advance.

public class DemoController : Controller
{
private DemoRestfulClient demoRestfulClient = new DemoRestfulClient();
public ActionResult Index()
{
var Result1 = demoRestfulClient.AdditionJava2().Result;
return Json(Result1);
}
}
The above method will return a json object .
You have wanted to get the json object, right? :)
You have to parse the Json object in order to separately view the content in json.
By using ajax, you can get the content of the json object separately.
For an example,
$.ajax({
url: $("#head").val() + "/Template/updatedTmpltView",
dataType: "html",
data: {},
type: "POST",
success: function (msg) {
data = $.parseJSON(msg)
var name = data.FieldName;
var type = data.FieldType;
var id = data.FieldId;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
In the success (msg), you get the json object as **msg**.
data will include the parsed json object and you can obtain necessary data by data.yourFieldName
Hope this helped you! :)

Related

Severity Code Description Project File Line Supcannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings'

cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings'
code
public JsonResult Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json(new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
The second parameter for Json method in Web API controller is incorrectly assigned, since ApiController Json method requires JsonSerializerSettings as second argument:
protected internal JsonResult<T> Json<T>(T content, JsonSerializerSettings serializerSettings)
{
......
}
The MVC controller counterpart for Json method is shown below:
protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
......
}
In this case, if the controller class containing Get method above extends ApiController, you need to change 2 return Json statements to return new JsonResult as given below:
public class ControllerName : ApiController
{
public JsonResult Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
// return JsonResult here
return new JsonResult()
{
Data = new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate }},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
catch (Exception Ex)
{
}
// return JsonResult here
return new JsonResult()
{
Data = new { success = false },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
If you want to use MVC controller when returning JSON instead, change ApiController to Controller class from System.Web.Mvc namespace and keep return Json(...) there.
Similar issue:
JSON return error with ASP

The operation cannot be completed because the DbContext has been disposed In Mqsql and Entity Framework

I am doing From dropdown selection, I fill textboxes with the Json Value. Action() Method work fine It return Json value but page not populate these value to TextBoxes control. When i use Developer Tool then i get, it throw a Error "The operation cannot be completed because the DbContext has been disposed."
Controller
private hcEntities db = new hcEntities();
// GET: Chains
public ActionResult Index()
{
ViewData["chain_name"] = new SelectList(db.chains, "code", "name");
return View(db.chains.ToList());
}
//Action Function callby javascript
[HttpPost]
public ActionResult Action(string code)
{
using (var ObjDb = new hcEntities())
{
var query = from c in ObjDb.chains
where c.code == code
select c;
return Json(query);//Return Json Result
}
}
View:-
<script type="text/javascript">
function Action(code) {
$.ajax({
url: '#Url.Action("Action", "Chains")',
type: "POST",
data: { "code": code },
"success": function (data) {
if (data != null) {
var vdata = data;
$("#ChainName").val(vdata[0].name);
$("#ChainCode").val(vdata[0].code);
$("#username").val(vdata[0].username);
}
}
});
}
Try return Json(query.FirstOrDefault());
Use IDisposable again in the GET Controller:
// GET: Chains
public ActionResult Index()
{
using (var ObjDb = new hcEntities())
{
ViewData["chain_name"] = new SelectList(ObjDb.chains, "code", "name");
return View(ObjDb.chains.ToList());
}
}

JSON posted to MVC Controller is null

Here is my jQuery which looks at an HTML table and gets an id from the tr and an input field value and puts them in an object to be json stringified and posted to an MVC controller. I am using jQuery 1.8.2
var rowdata = [];
$('table').find('tr').each(function () {
myjson = [];
item = {}
item["id"] = $(this).attr('id');
item["reason"] = $(this).find('input').val();
myjson.push(item);
rowdata.push(myjson);
});
jsonstring = JSON.stringify(rowdata);
$.ajax({
url: '#Url.Action("AbsentReason", "Attendance")',
data: jsonstring,
type: 'POST',
traditional: true,
contentType: 'json',
success: function (data) {
$('#message').html("Reason was updated");
}
});
This is the resulting JSON which checks valid.
[[{}],[{"id":"6","reason":""}],[{"id":"7","reason":""}],[{"id":"15","reason":""}],[{"id":"23","reason":""}],[{"id":"29","reason":""}],[{"id":"30","reason":""}],[{"id":"31","reason":""}],[{"id":"35","reason":""}],[{"id":"40","reason":""}],[{"id":"41","reason":""}],[{"id":"42","reason":""}],[{"id":"48","reason":""}],[{"id":"49","reason":""}],[{"id":"50","reason":""}],[{"id":"51","reason":""}],[{"id":"52","reason":""}],[{"id":"53","reason":""}],[{"id":"54","reason":""}],[{"id":"55","reason":""}],[{"id":"56","reason":""}],[{"id":"57","reason":""}],[{"id":"58","reason":""}],[{"id":"59","reason":""}],[{"id":"60","reason":""}],[{"id":"61","reason":""}],[{"id":"62","reason":""}],[{"id":"63","reason":""}],[{"id":"74","reason":""}],[{"id":"75","reason":""}],[{"id":"80","reason":""}],[{"id":"81","reason":""}],[{"id":"87","reason":""}],[{"id":"88","reason":""}],[{"id":"90","reason":""}],[{"id":"91","reason":""}],[{"id":"105","reason":""}],[{"id":"106","reason":""}],[{"id":"107","reason":""}],[{"id":"108","reason":""}],[{"id":"110","reason":""}],[{"id":"111","reason":""}],[{"id":"119","reason":""}]]:
This is the start of my controller.
[HttpPost]
public ActionResult AbsentReason(string jsonstring)
{
return View("Index");
}
The jsonstring parameter is always null. Can anyone see what is wrong?
UPDATE
This is my new controller based on the comments to use a model and allow MVC to do the work for me.
[HttpPost]
public ActionResult AbsentReason(IEnumerable<VMAttendance> jsonstring)
{
return View("Index");
}
and my viewmodel
public class VMAttendance
{
public int PersonID
{
get;
set;
}
public string Reason
{
get;
set;
}
}
The parameter is still null. I also update my jQuery in an attempt to send the correct json.
var data = $('table').find('tr').map(function () {
var id = $(this).attr('id');
var reason = $(this).find('input').val();
var rowdata = { "PersonID": id, "Reason": reason };
return rowdata;
}).get();
$.ajax({
url: '#Url.Action("AbsentReason", "Attendance")',
data: data,
type: 'POST',
traditional: true,
contentType: 'json',
success: function (data) {
$('#message').html("Reason was updated");
}
});
I tried to send some test json to the controller but the parameter is still null.
var data = '{"PersonID":"6","Reason":""},{"PersonID":"7","Reason":""}'
assuming you have an MVC model as follow
public class MyModel
{
public int ID {get;set;}
public string Reason {get;set;}
}
if you modify your action method signature to
public ActionResult AbsentReason(IEnumerable<MyModel> json)
when you post back your json object, the json serializer will deserialize your json into an IEnumerable of MyModel.
I got this working by changing the contentType from 'json' to 'application/json; charset=utf-8' and removing the first empty object in my json which was created from an extra tr in the table for the header. The json looked like
[{},{"PersonID":"6","Reason":""},{"PersonID":"7","Reason":""}]
when it should look like this
[{"PersonID":"6","Reason":""},{"PersonID":"7","Reason":""}]
My controller looks like this and works nice.
[HttpPost]
public ActionResult AbsentReason(IEnumerable<VMAttendance> jsonstring)
{
return View("Index");
}
Thanks Duy for your assistance!
change the contentType in your ajax object to string.
i'm curious as to why you would want to treat your json as string and not as object. Normally I would have a C# viewmodel and let the serializer map the json object to that C# view model in my controller

Json deserialization Mvc 4 Knockout js

I'm having problems when I try to deserialize json into a object in MVC4.
I have a Viewmodel:
public class TestViewModel
{
public string Code { get; set; }
}
On the view I get the model and serialize the object using Json.net
var Vm = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.GetResults = function() {
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: ko.mapping.toJSON(self),
success: function(data) {
alert('OK');
}
});
};
};
var viewModel = new Vm(#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
ko.applyBindings(viewModel);
My problem is when I call GetResults the action in the controller, all properties are null.
My Json is:
{"Code":"TestCode"}
I have the same structure in a MVC3 project and works fine. I'm missing something in MVC4?
Cheers!
We've noticed that in some scenarios jQuery will embed the data in a Form in the Request. When this happens, the values are not automatically mapped to the object type in the Controller method.
To get around this, you need to do two things:
1) Check to see if the data is serialized. I found an easy way to do this and dumped it in an extension method:
public static class WebContextExtensions
{
public static bool IsDataSerialized(this HttpContext context)
{
return context.Request.Params.AllKeys[0] == null;
}
}
2) IF IsDataSerialized returns true, you need to deserialize the data into your object type. We wrote a GenericDeserializer method to do that as well:
public class GenericContextDeserializer<T> where T : new()
{
public T DeserializeToType(HttpContext context)
{
T result = new T();
if (context != null)
{
try
{
string jsonString = context.Request.Form.GetValues(0)[0].ToString();
Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();
result = js.Deserialize<T>(new Newtonsoft.Json.JsonTextReader(
new System.IO.StringReader(jsonString)));
}
catch (Exception ex)
{
throw ex;
}
}
else
throw new NullReferenceException();
return result;
}
}
Now put it all together in your Controller method:
[HttpPost]
[HttpOptions]
public HttpResponseMessage MyAction(JsonData data)
{
var results = Request.CreateResponse();
try
{
data = new GenericContextDeserializer<JsonData>().DeserializeToType(HttpContext.Current);
// do stuff with data
results.StatusCode = HttpStatusCode.OK;
}
catch (Exception ex)
{
results.StatusCode = HttpStatusCode.InternalServerError;
}
return results;
}
If you want more detail, it's in the second half of a blog post I wrote.

Restlet implementing post with json receive and response

First, what i wanted to know is what i am doing is the right way to do it.
I have a scenario where i have will receive a json request and i have to update the database with that, once the db is updated i have to respond back with the json acknowledgment.
What i have done so far is create the class extending application as follows:
#Override
public Restlet createRoot() {
// Create a router Restlet that routes each call to a
// new instance of ScanRequestResource.
Router router = new Router(getContext());
// Defines only one route
router.attach("/request", RequestResource.class);
return router;
}
My resource class is extending the ServerResource and i have the following method in my resource class
#Post("json")
public Representation post() throws ResourceException {
try {
Representation entity = getRequestEntity();
JsonRepresentation represent = new JsonRepresentation(entity);
JSONObject jsonobject = represent.toJsonObject();
JSONObject json = jsonobject.getJSONObject("request");
getResponse().setStatus(Status.SUCCESS_ACCEPTED);
StringBuffer sb = new StringBuffer();
ScanRequestAck ack = new ScanRequestAck();
ack.statusURL = "http://localhost:8080/status/2713";
Representation rep = new JsonRepresentation(ack.asJSON());
return rep;
} catch (Exception e) {
getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
}
My first concern is the object i receive in the entity is inputrepresentation so when i fetch the jsonobject from the jsonrepresentation created i always get empty/null object.
I have tried passing the json request with the following code as well as the client attached
function submitjson(){
alert("Alert 1");
$.ajax({
type: "POST",
url: "http://localhost:8080/thoughtclicksWeb/request",
contentType: "application/json; charset=utf-8",
data: "{request{id:1, request-url:http://thoughtclicks.com/status}}",
dataType: "json",
success: function(msg){
//alert("testing alert");
alert(msg);
}
});
};
Client used to call
ClientResource requestResource = new ClientResource("http://localhost:8080/thoughtclicksWeb/request");
Representation rep = new JsonRepresentation(new JSONObject(jsonstring));
rep.setMediaType(MediaType.APPLICATION_JSON);
Representation reply = requestResource.post(rep);
Any help or clues on this is hight appreciated ?
Thanks,
Rahul
Using just 1 JAR jse-x.y.z/lib/org.restlet.jar, you could construct JSON by hand at the client side for simple requests:
ClientResource res = new ClientResource("http://localhost:9191/something/other");
StringRepresentation s = new StringRepresentation("" +
"{\n" +
"\t\"name\" : \"bank1\"\n" +
"}");
res.post(s).write(System.out);
At the server side, using just 2 JARs - gson-x.y.z.jar and jse-x.y.z/lib/org.restlet.jar:
public class BankResource extends ServerResource {
#Get("json")
public String listBanks() {
JsonArray banksArray = new JsonArray();
for (String s : names) {
banksArray.add(new JsonPrimitive(s));
}
JsonObject j = new JsonObject();
j.add("banks", banksArray);
return j.toString();
}
#Post
public Representation createBank(Representation r) throws IOException {
String s = r.getText();
JsonObject j = new JsonParser().parse(s).getAsJsonObject();
JsonElement name = j.get("name");
.. (more) .. ..
//Send list on creation.
return new StringRepresentation(listBanks(), MediaType.TEXT_PLAIN);
}
}
When I use the following JSON as the request, it works:
{"request": {"id": "1", "request-url": "http://thoughtclicks.com/status"}}
Notice the double quotes and additional colon that aren't in your sample.