Example on consuming JSON in Play Framework views - json

I am trying to make the switch in a controller from sending JPA retrieved items as a List to the template engine to now send these as JSON.
I would prefer to use the flexJSON library for the task.
What I have is a Application controller with the method:
public static Result index() {
... Processing ...
flash("success", "Items have been processed");
return ok(index.render(Item.all()));
}
and a view index.scala.html like this one:
#(items: List[Item])
#import helper._
#main("Item list") {
<h1>#items.size() items(s)</h1>
<ul>
#for(item <- items) {
<li>
#item.title
</li>
}
</ul>
}
These to perfectly show an unnumbered list of all the processed items.
Now, if I changed the controller to using flexJSON like so:
public static Result getItems() {
List<Item> items = Item.all();
String s = new JSONSerializer().exclude("*.class", "description").serialize(items);
flash("success", "Messages have been processed");
return ok(index.render(s));
}
How would i program my template in order to consume that json string of items?
i tried to follow this blog on the matter, http://www.jamesward.com/2011/12/11/tutorial-play-framework-jpa-json-jquery-heroku, but fall short on how to consume the json in my template views... any code example would be greatly appreciated.

Just Sample it may help you.
application.conf
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
ebean.default="models.*"
routes
GET / controllers.Application.index()
GET /cities controllers.Application.all()
Controller => Application.java
package controllers;
import play.*;
import play.mvc.*;
import models.City;
import play.libs.Json;
import views.html.*;
public class Application extends Controller {
public static Result index() {
return ok(index.render());
}
public static Result all(){
City pune=new City();
pune.name="pune";
pune.save();
City mumbai=new City();
mumbai.name="mumbai";
mumbai.save();
return ok(Json.toJson(City.all()));
}
}
Template => index.scala.html
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
$(function(){
get_cities();
});
var get_cities = function() {
$.ajax({
url: '#routes.Application.all()',
processData:false,
type: 'GET',
beforeSend:function(jqXHR, settings){
jqXHR.setRequestHeader("Content-Type", "application/json");
},
success: function(data, textStatus, jqXHR){
process_cities(data);
},
error: function(jqXHR, textStatus, errorThrown){
},
complete: function(jqXHR,textStatus){
}
});
};
var process_cities = function(cities){
var contentDiv=$("div#content");
contentDiv.append("<ul>");
$.each(cities,function(i,city){
contentDiv.append("<li>" + city.name + "</li>");
});
contentDiv.append("</ul>");
};
</script>
</body>
</html>

Related

cannot get parameters from ajax call to controller razor

Simple usecase - get PartialView dynamically from AJAX call to update div in my main page after input select (dropdownlist) changed value.
Steps I took:
Created view (only, wihtout PageModel) with model declared with #model ViewModelCreateOperation.
Created checkbox on main page:
<select class="form-control" asp-items="#(new SelectList(Model.allExistingOperations))" onchange="PopulateForm(this.value); return false;"></select>
created scripts on main page:
<script>
function PopulateForm(value) {
var dataToPost = "{ operationName:" + value + "}";;
$.ajax({
type: "post",
url: '#Url.Content("/MeaningOfLifeRoutedName")',
data: dataToPost ,
contentType : 'application/json; charset=UTF-8',
success: function (data) {
$('#lubieplacki').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}
</script>
created Controller in Controllers folder to return PartialView (becouse I cannot use "return PartialView("someview", someModel)" with PageModel already used as a inherit class.
namespace MyMysteriousApplication.Controllers
{
[Route("MeaningOfLifeRoutedName")]
public class MeaningOfLifeChangesController : Controller
{
private readonly MyMysteriousApplication.Models.TTSCDBContext _context;
public MeaningOfLifeChangesController(MyMysteriousApplication.Models.TTSCDBContext context)
{
_context = context;
}
public ViewModelCreateOperation viewModelCreateOperation { get; set; }
public IActionResult Index()
{
return RedirectToPage("../Index");
}
[HttpPost]
public ActionResult getMeaningOfLife(string operationName)
{
viewModelCreateOperation = new ViewModelCreateOperation();
viewModelCreateOperation = new ViewModelCreateOperation();
viewModelCreateOperation._entitiesSelectListItem = _context.Entities
.Select(a => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem()
{
Value = a.Id.ToString(),
Text = a.EntityName
}).OrderByDescending(u => u.Text)
.ToList();
viewModelCreateOperation.MeaningOfLifeChanges = _context.MeaningOfLifeChanges.Where(u => u.OperationName.Contains(operationName)).OrderBy(u => u.ChangeId).FirstOrDefault();
return PartialView("../projectManagement/partialViewCreateNewMOL", viewModelCreateOperation);
}
}
}
Primary question:
I got null in parameters - I don't get why:
Bonus question:
I couldn't invoke my controller in any way (tried "/MeaningOfLifeChangeController/getMeaningOfLife" or "/MeaningOfLifeChange/getMeaningOfLife", with "~/MeaningOfLifeChangeController/getMeaningOfLife" and others combinations), so I added [Route("MeaningOfLifeRoutedName")] and [HttpPost] before method. I don't get why...
in Startup I have added controllers to initialize (JSON is for other stuff(API)):
services.AddControllersWithViews().
AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.MaxDepth = 150;
}).AddRazorRuntimeCompilation();
It's not my answer, but Jiadong Meng helped me in ASP .NET Forums. I'm posting His answer:
Since the data you want to send is just a string type data, you need to stringify it like below.
var dataToPost = JSON.stringify(value);
Then in your Action, you should also add [FromBody] attribute.
public ActionResult getMeaningOfLife([FromBody]string operationName)

get html 5 date input field and pass to .net controller

On my razor page, I have a simple date picker that looks like this:
<input type="date" name="lessonsStart">
How would I go about getting the value of that and sending it to my controller?
Whenever I send data to my controller from a razor page, the format always looks something like this:
<a asp-action="LessonIndex" asp-route-id="#item.Id">#Html.DisplayFor(modelItem => item.Name)</a>
which sends an "item.Id" to my controller called LessonIndex().
So I'm not sure how I'd get the date value and send it.
The controller looks like this:
public IActionResult LessonIndex(datetime startDate) {
var response = getLessons(startDate);
return response.Results;
}
Is there a specific format I need to use?
Note that the date is not used in a model, it just needs to be sent to a controller.
Thanks!
Assuming this is related to mvc the controller would have a method associated with the post that you would perform to get the data from the form back to the controller. This uses javascript to post data to your LessonIndex() method.
<!--top of your page.-->
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<input type="date" id="lessonStart" name="lessonStart" />
<input type="Submit" id="PostButton" name="PostButton" Value="Go" />
#section Scripts{ // razor section at the bottom of mvc page 'cshtml'.
<script type="javascript">
$(function(){
$("#PostButton").click(function(){
var url = '#Url.Action("LessonIndex", "Lesson")'; //assuming controller is named Lesson
var date= new Date(this.value).ToDateString();
$.ajax({
url: url,
type: "POST",
data: "lessonStart=" + date,
headers:{
"RequestVerificationToken": '#GetAntiXsrfRequestToken()'
},
success: function(response){
console.log(response);
},
error: function(e){
console.log(e.error);
}
});
});
}
</script>
}
this also assumes that the method looks like this
public class LessonController : Controller{
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult LessonIndex(DateTime lessonStart){
var response = getLessons(lessonStart);
return View(response.results);
}
}
" Note that the date is not used in a model, it just needs to be sent to a controller. "
You could use the ajax to pass the date as QueryString to the method in the controller.
Here is the test example
<input type="date" name="lessonsStart" id="lessonsStart">
#section Scripts
{
<script type="text/javascript">
$("#lessonsStart").change(function () {
var inputDate = new Date(this.value).toDateString();
$.ajax({
type: "post",
url: "/ControllerName/lessonindex?startdate=" + inputDate,
success: function () { }
});
});
</script>
}
The method in controller
[HttpPost]
public IActionResult LessonIndex(DateTime startDate)
{
return Json(startDate);
}
<div class="demo-section k-content">
<h4>Remind me on</h4>
#(Html.Kendo().DateTimePicker()
.Name("datetimepicker")
.Value(DateTime.Now)
.HtmlAttributes(new { style = "width: 100%", title = "datetimepicker" })
.DateInput()
)
</div>

how to insert JSON array into MySQL using mvc spring

Hi I am new in spring And developing a module of POST.
How to insert JSON array in db.
can you please give me the idea how to solve this issue.
I have also an example to show you this.
link:- http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-json-data-code-example
Here the controller code
#RequestMapping(value = "/create1", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
BillingModel addbillingmodel(#RequestBody BillingModel billingmodel) {
try {
billingmodel.getItemid();
billingmodel.getQuantity();
dataServices.addEntity(billingmodel);
return billingmodel;
} catch (Exception e) {
e.printStackTrace();
return billingmodel;
}
}
}
Here is my html page with JSON.
<!DOCTYPE html>
<html data-ng-app="serviceModule">
<head>
<meta charset="ISO-8859-1">
<title>AngularJS POST Spring MVC</title>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
<script type="text/javascript">
var serviceModule = angular.module('serviceModule', []);
serviceModule.controller("AngularJSPostController", function($scope, $http) {
$scope.variable = "AngularJS POST Spring MVC Example:";
var dataObj = {
"itemid" : "11",
"quantity" : "22",
};
var response =
$http.post('/CRUDWebAppMavenized/billing_bakery/create1', dataObj);
response.success(function(data, status, headers, config) {
$scope.responseData = data;
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
});
</script>
</head>
<body data-ng-controller="AngularJSPostController">
<div>
<h4>{{variable}}</h4>
<b>You had sent below data through post:</b>
<p>Response: {{responseData}}</p>
</div>
</body>
</html>
I have to multiple data in a row.
1.In your BillingModel class create following methods -
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public String toJson() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(this);
return json;
}
2.You should have blob types of columns to store JSON
3.And in Your DAO class when you call addEntity , do something like this -
final MapSqlParameterSource sqlParams = new MapSqlParameterSource()
.addValue("item_json",billingModel.toJson().getBytes("UTF-8"));
You can also refer.
Converting Java objects to JSON with Jackson

to pass parameter to web api through ajax call

I have below ajax query which returns me json from controller
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=1",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
the controller action is as below
[System.Web.Http.ActionName("GetHomeTab")]
public HomeTabModel GetHomeTab(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new HomeTabModel
{
HomeDesc = outlet.BizHomeDesc,
HomeTabText = outlet.BizHomeTabText
};
}
Now my question is: curently i am sending hard coded value of bizId to web api. I want to send this value dynamically. How can i achieve this? I have that value in my route config file. The code is as below-
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{bizId}",
defaults: new { controller = "Home", action = "Index", bizId = 1 }
);
}
I am new to this. Please help! Thanks in advance!
no, actually after much research, i came up with this solution and this works fine for me....
In controller,
public ActionResult Index(int bizId)
{
ViewBag.BizId = bizId;
return View();
}
and in View,
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=#ViewBag.BizId",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
You can pass a data object as part of the GetJson call.
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab",{bizId : 1},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
Taking this one step further you could wrap this in a function.
function makeCall(id)
{
$.getJSON("api/OutletPOC/GetHomeTab",{bizId : id},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
}
Also look into using promises.
$.getJSON().then().done();

zend_rest + mysql + backbone

I implemented a RESTful application with Zend_Rest that saves info in a mysql db.
I'm going to handle the view with Backbone.js.
I'm looking for just a simple CRUD example. How to do that?
I didn't found any examples with Zend_Rest+Backbone, and the idea is to create it here, together.
UPDATE 0.1
How can I send (from backbone) and read (in the get/put/delete controller) the parameters?
CONTROLLER (modules>api>controllers>BackboneController.php)
class Api_BackboneController extends Zend_Rest_Controller
{
public function init(){
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
public function headAction(){
$this->getResponse()->setBody(null);
}
public function optionsAction(){
$this->getResponse()->setBody(null);
$this->getResponse()->setHeader('Allow', 'OPTIONS, HEAD, INDEX, GET, POST, PUT, DELETE');
}
// called from backbone with "read"
public function indexAction(){
// get the params
$resp = json_decode(file_get_contents('php://input'));
// send the same response
$this->getResponse()->appendBody(json_encode($resp));
}
// I can't reach this one from backbone, WHY?
public function getAction(){}
// called from backbone with "update"
public function putAction(){}
// called from backbone with "delete"
public function deleteAction(){}
}
VIEW (modules>default>views>scripts>index.phtml)
var MyModel = Backbone.Model.extend({
defaults: {
text: "default text"
},
url: "/base/api/backbone",
options: {
success: function(data){
console.log(data);
},
error: function(x, t, e){
console.log("error: " + t + ", " + e);
}
}
});
var myModel = new MyModel();
Backbone.sync("read", myModel, myModel.options);
})(jQuery);