I am new to Spring mvc3 portlet and dojo. I am trying to populate select dropdown with JSON data when jsp is loaded. I want to use dojo and give ajax call to controller and return JSON when jsp is loaded. Any tips will be helpful.
#Controller
#RequestMapping("/yourController")
public class YourController
{
#RequestMapping(value="/combo/{id}", method=ReqestNethod.GET)
public String getDropDownData(#ParamValue("id") long id)
{
List<Combo> combos = commonDao.getCombos(id);
String json = JsonUtil.toJson(combos); // or whichever way you use
return json;
}
}
Send requests from dojo to this url
<your-context-path>/yourController/combo/1
where 1 is your combo id.
I haven't checked the syntax here.. Wrote it blind. You might get compilation errors.
I get data in below format
How do I populate dojoType="xwt.widget.form.FilteringSelect"
{"ValuesDTO": {"items": [{},{"default": {"size": 5},"int": 10,"string": "Product1","string": "Product1 ","string": "product3","string": "product4","string": "product5"}]}}
I am sending dat in bean--->DTO--->List
Related
I be straight to the point. I am in the process of converting ASP.Net web services into DotNetCore 2.1 services. My question is very simple. How do I get json output from a string (with a GET verb)?
I'm new at this, but almost every piece of documentation and recommendations do not work with DotNetCore.
Obviously, the following will not work:
[HttpGet]
public string Get()
{
return "{\"country_code\":\"US\",\"country_name\":\"United States\",\"region_name\":\"California\",\"city_name\":\"Los Angeles\",\"latitude\":\"34.052230\",\"longitude\":\" - 118.243680\",\"zip_code\":\"90001\",\"time_zone\":\" - 08:00\"}";
}
I just need to convert this string (or tell the client) that I want the output in json. The following does not work either - got a squiggly line under the "Json(" method and, for the life of me, can't find a reference to make it go away (I pulled it from an example, so they must be using a 3rd party json parsing library or there's a reference that I'm missing)
[HttpGet]
public JsonResult Get()
{
return Json("{\"country_code\":\"US\",\"country_name\":\"United States\",\"region_name\":\"California\",\"city_name\":\"Los Angeles\",\"latitude\":\"34.052230\",\"longitude\":\" - 118.243680\",\"zip_code\":\"90001\",\"time_zone\":\" - 08:00\"}", "application/json");
}
Ideally, I'd like to serialize an object to json, but figured I'd start with something ridiculously simple.
Anywho, if anyone can help.
If you don't already have a strongly typed model, you can build an anonymous type and return that from the controller
Simple Example.
public class MyController: Controller {
[HttpGet]
public IActionResult Get() {
var model = new {
country_code = "US",
country_name = "United States",
region_name = "California",
city_name = "Los Angeles",
latitude = 34.052230,
longitude = -118.243680,
zip_code = 90001,
time_zone = "- 08:00"
};
return Ok(model); //200 OK with content
}
}
In more complex scenarios you would get your objects from a data source.
No library needed, the framework out of the box will serialize the object(s) into JSON for you by default unless otherwise configured.
If you insist on passing a manually formatted string then use the ContemntResult object. Pass it the string and the content type.
[HttpGet]
public IActionResult Get() {
string json = "{\"country_code\":\"US\",\"country_name\":\"United States\",\"region_name\":\"California\",\"city_name\":\"Los Angeles\",\"latitude\":\"34.052230\",\"longitude\":\" - 118.243680\",\"zip_code\":\"90001\",\"time_zone\":\" - 08:00\"}";
return Content(json, new MediaTypeHeaderValue("application/json"));
}
Reference Format response data in ASP.NET Core Web API
Forcing a Particular Format
If you would like to restrict the response formats for a specific action you can apply the
[Produces] filter. The [Produces] filter specifies the response
formats for a specific action (or controller). Like most Filters, this
can be applied at the action, controller, or global scope.
[Produces("application/json")]
public class AuthorsController
The [Produces] filter will force all actions within the
AuthorsController to return JSON-formatted responses, even if other
formatters were configured for the application and the client provided
an Accept header requesting a different, available format.
Don't return string but object. So result of your actions are json string this is why you will get string in JSON and not an object
Make sure that your client is sending header "Content-Type": "application/json".
[HttpGet]
public Address Get()
{
return new Address{ CountryCode = "US"} ;
}
I have a ASP.NET MVC Controller C# and inside I have the following method:
public JsonResult PlayersData()
{
List<Player> players = new List<Player>();
// here some code to fill players list
// ...
return Json(players, JsonRequestBehavior.AllowGet);
}
I would like to send the Json compressed, I mean the List because the json is heavy about 12MB.
I don't want to enable IIS compression, I need to do it within the same code.
Any clue?
The requirement is letting users to upload a list of tickets with something like:
#RequestMapping(value="/tickets", method=RequestMethod.POST)
public void uploadTickets(
#RequestBody List<Ticket> tickets) {
// Do something with the list of tickets
}
I know how to upload a single ticket. I just need to create a html form with three fields (section, row, seat) and a submit button. Then spring will automatically convert the uploaded form to a Ticket object. But I am not sure how to upload a list of Tickets with Spring controllers. Any help? Thanks!
This depends on your configuration. Assuming a normal spring configuration.
You normally upload a single ticket with a json request
{ "section":"", "seat":"", "row":"" }
To get the list of tickets, just use a json array.
[
{ "section":"", "seat":"", "row":"" },
.......,
{ "section":"", "seat":"", "row":"" }
]
To get the data into this format, it of course depends on the front end. You might need to do some javascript on the frontend to get it into this format.
you can just put it in model object and get the data from the model object as given below example
#RequestMapping(value="/tickets", method=RequestMethod.POST)
public String uploadTickets(Map<String, Object> model) {
Ticket t = new Ticket();
model.put("ticket", t);
return "page";//return page or redirect.
}
I have data in my apicontroller in following way-
public class OutletPOCController : ApiController
{
OutletPOCContext db = new OutletPOCContext();
[System.Web.Http.ActionName("GetTabText")]
public TabTextModel GetTabText(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new TabTextModel
{
HomeTab = outlet.BizHomeTabText,
AboutTab = outlet.BizAboutTabText,
TimingsTab = outlet.BizTimingsTabText,
};
}
And now i want to retrieve this data into my view. How shall i create view for this controller and pass the above data? What will be my action method? I am new to webapi and json. Any help is appreciable! Thanks in advance!
The API controller dosent really have views in the sense that you create a cshtml page that takes care of how you display your data. The purpose of the ApiController is simply to return data in the format that you want to consume it.
Basically the API exposes raw data to the web, you consume it in some way, and then display it..
I use something similar to this to load data dynamically into a web page.
Just a simple web api that returns data to the client.
public class APIController : ApiController
{
[HttpGet]
[HttpPost] // allow both post and get requests
public IEnumerable<String> GetData()
{
return new List<string>() { "test1", "test2" };
}
}
When you browse to the API method above it returns this xml data
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>test1</string>
<string>test2</string>
</ArrayOfstring>
Which I get using Jquery and do what I please with (http://api.jquery.com/jQuery.get/):
$.get("/api/GetData", function(data) {
alert("Data Loaded: " + data);
});
Examples of XML parsing with JS/Jquery:
http://tech.pro/tutorial/877/xml-parsing-with-jquery
http://www.kawa.net/works/js/jkl/parsexml-e.html
If you are simply looking to get data into a regular view and work with it there without going through javascript I wouldent use a webapi, but instead get the data in the controller and send it to the view for displaying (ASP MVC4 - Pass List to view via view model).
You can also check out the ViewBag container for passing random odd data to the view http://goo.gl/03JTR
On the off chance you really do want to render your data in a view, check this out: Web API - Rendering Razor view by default?
It's like user click a link and in the Spring controller class a method will respond to the request with a JSON object and also a view name (meaning, it should return but not only a JSON object but also a HTTP view which hold that JSON object, so #ResponseBody may not enough)? Do we have to split it up into two methods (one for view and the other for JSON object)? Any ideas will be appreciated.
Normally we have
#RequestMapping(value="/someValue")
public #ResponseBody someMethod1(#RequestParam String param){
.....
return someJSONObject
}
To handle JSON object, and
#RequestMapping(value="/someValue")
public String someMethod2(#RequestParam String param){
.....
return someViewInString;
}
To return the view.
How can we combine them together?
You should return the view with a placeholder for the JSON.
In the controller code, create the JSON programatically, convert it to String format and then put it in the model (let's call it json_string)
In the view there should be a placeholder for the JSON string, something like:
<!-- other view stuff -->
var v = ${json_string};
<!-- more view stuff -->