how to pagination JSONResult in MVC with ajax url data loading? - json

I have a problem in pagination with a json result data in MVC.
Below code is my ajax data loading:
jQuery.ajax({
url: "/Products/Search",
type: "POST",
dataType: "json",
success: function (data) {
displayData(data);
},
error: function (errdata, errdata1, errdata2) { $('#ProductList').html("Error in connect to server" + errdata.responseText); }
and my controller JsonResult is below:
public JsonResult List()
{
tbl = db.tblProducts;
return Json(tbl, JsonRequestBehavior.AllowGet);
}
I can recive data from above ajax data loading successfully, but I can't pagination it.
Please help me.
Thank you.

There is no code for Pagination,Do you want to do client side pagination or server side
Thinking your devloping an ASP.Net MVC application
Server side pagnation : You can load the specific number of records alone.
Using Skip and Take functionlitys
public JsonResult GetOrders(int pagesize, int pagenum)
{
var query = Request.QueryString;
var dbResult = db.Database.SqlQuery<Order>(this.BuildQuery(query));
var orders = from order in dbResult
select new Order
{
ShippedDate = order.ShippedDate,
ShipName = order.ShipName,
ShipAddress = order.ShipAddress,
ShipCity = order.ShipCity,
ShipCountry = order.ShipCountry
};
var total = dbResult.Count();
orders = orders.Skip(pagesize * pagenum).Take(pagesize);
var result = new
{
TotalRows = total,
Rows = orders
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Client side pagination : Load the entire records to your view from there implement pagination
Sample code : http://jsfiddle.net/rniemeyer/5xr2x/

Database db = new Database();
public int PageSize = 5;
public int VisiblePageCount = 5;
public JsonResult Search(int page = 1)
{
var model = new ModelName();
var tbl = db.tblProducts;
var renderedScheduleItems =(tbl.Skip((page - 1) * PageSize)
.Take(PageSize)
.ToList());
model.Products = renderedScheduleItems;
model.PagingDetail = new PagingDetail()
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = items.Count,
VisiblePageCount = VisiblePageCount
};
return Json(model, JsonRequestBehavior.AllowGet);
}

Related

Not getting the LINQ join query result in Ajax success method from Json Result using MVC however the result is shown correctly

I am trying to pass LINQ join query result(joining three tables ) from the controller to Ajax success function from Json Result but I am not getting any value means success function did not run and it executes error function . the query generated the correct result and also when I placed the breakpoint on return Json(query) or return new JsonResult{ Data = query, JsonRequestBehavior = JsonRequestBehavior.AllowGet };, the query variable contains the data . the problem is that the generated query result is not passed from the controller to the ajax function. I have tried other possible solutions but did not get any success.
Note : I have created model class to store the join query result.
any guidance regarding this will highly be appreciated
Thanks in advance.
here my controller code
[HttpPost]
public JsonResult getscore(int val)
{
Debug.WriteLine("checking {0}", val);
var g = val;
List<Participant_info> p_details = context.Participant_info.ToList();
List<Participant_enrolled> e_details = context.Participant_enrolled.ToList();
List<Contest_marking> mark = context.Contest_marking.ToList();
var query = (from p in p_details
join e in e_details on p.stud_id equals e.stud_id
join m in mark on e.E_id equals m.E_id
select new ScoreViewModel
{
partVm = p,
enrollVm = e,
markVm = m
}).ToList();
foreach (var u in query)
{
Debug.WriteLine("name {0} mark{1} Contest_id {2} ", u.partVm.stud_name, u.markVm.C1st_marks, u.enrollVm.Contest_id);
}
return Json(query, JsonRequestBehavior.AllowGet);
//return new JsonResult { Data = query, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Model class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CEN_CONTEST_MGT_SYSTEM.Models
{
public class ScoreViewModel
{
public Participant_info partVm { get; set; }
public Participant_enrolled enrollVm { get; set; }
public Contest_marking markVm { get; set; }
}
}
View code
#model IEnumerable<CEN_CONTEST_MGT_SYSTEM.Models.ScoreViewModel>
#{
ViewBag.Title = "score";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>score</h2>
#Html.DropDownList("Trial", "--- Tous ---")
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$("#Trial").change(function () {
val = $("#Trial").val();
alert("fff" + val);
//var data = JSON.stringify({
// 'val': val
//});
$.ajax({
type: "POST",
url: "/judge_dashboard/getscore",
data: JSON.stringify({'val': val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
processData: false,
cache: false,
success: function (data) {
alert("hello");
},
error: function () {
alert("error");
}
})
})
</script>
try to change the action
public ActionResult<List<ScoreViewModel>> getscore(int val)
{
... your code
return Ok(query);
}
When using this:
select new ScoreViewModel
{
partVm = p,
enrollVm = e,
markVm = m
}
Likely what's happening is the serialization process is also processing all of your child objects, and may be running into a problem with that. Is there any error that you are receiving? I have a feeling the serialization process might be complicating it.
To test that, try returning all the properties you need directly such as:
return Json(new {
x = vm.partVm.X,
y = vm.enrollVm.Y
}, JsonRequestBehavior.AllowGet);

mvc controller json return

i want to return an image in base64 from my controller to view using json.
public JsonResult changeProfile()
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
TBL_User item = _context.TBL_User.Find(userID);
UserModel model = new UserModel();
model.UserID = userID;
model.BinaryPhoto = item.BinaryPhoto;
return Json(new
{
??????????????'
},
JsonRequestBehavior.AllowGet);
}
what can i put there to return my image and display in the view?
thanks
Update controller
public JsonResult changeProfile()
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
TBL_User item = _context.TBL_User.Find(userID);
UserModel model = new UserModel();
model.UserID = userID;
model.BinaryPhoto = item.BinaryPhoto;
var base64 = Convert.ToBase64String(model.BinaryPhoto);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
return Json(new
{
Image = imgsrc
},
JsonRequestBehavior.AllowGet);
}
Update src for image in ajax success
$.ajax({
url: "/changeProfile",
success: function(data) {
$(".img-circle").attr('src', data.Image);
}
});

Pushing complete data from Spring Boot server through Web Socket to Client

I have a spring boot server and i am able to generate a streaming table on client side by sending json one after the another. The problem is if a user logs in say after 10 minutes, he is only able to access data starting from 10th minute i.e he is not able to access data from 0 to 10th minute. What i want is to push the data from 0th to 10th minute first and at the same time continue the streaming process. How can this be done? I am using jquery datatable to generate the table.
I am attaching the controller and client side html for reference
1) Controller
#Controller
public class ScheduledUpdatesOnTopic {
#Autowired
private SimpMessagingTemplate template;
int count=0;
#Scheduled(fixedDelay=500)
public void trigger() {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String str[] = {"name"+count,""+Math.round(Math.random()*100),"India"+Math.round(Math.random()*100),df.format(date)};
this.template.convertAndSend("/topic/message",str);
++count;
}
}
2) Client HTML
var _self = this;
$(document).ready(function() {
var message ;
$('#tbl').DataTable( {
data: message,
"aLengthMenu" : [[25,50,75,-1],[25,50,75,"All"]],
"pageLength" :25,
columns: [
{ title: "Name" },
{ title: "Age" },
{ title: "Country" },
{ title: "Date"}
]
});
subscribeSocket();
});
function addRow(message){
var table = $('#tbl').DataTable();
if(table && message ){
table.row.add(message).draw();
}
}
function subscribeSocket(){
var socket = new SockJS('/gs-guide-websocket');
var stompClient = Stomp.over(socket);
stompClient.connect({ }, function(frame) {
stompClient.subscribe("/topic/message", function(data) {
message = JSON.parse(data.body);
_self.addRow(message);
});
});
};
If you don't save previous sent datas, you can't send them back to new customers.
On the front side, you have to subscribe to an "history" resource and make a call to get it.
Front:
function subscribeSocket() {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
var firstCounterReceived = null;
stompClient.connect({}, function (frame) {
setConnected(true);
stompClient.subscribe('/topic/history', function (response) {
console.log(JSON.parse(response.body));
});
stompClient.subscribe('/topic/message', function (response) {
var message = JSON.parse(response.body);
if (firstCounterReceived == null) {
firstCounterReceived = message[0];
console.log(`Calling history endpoint with ${firstCounterReceived}`);
stompClient.send("/app/topic/history", {}, message[0]);
}
console.log(message);
});
});
}
Back:
#Controller
#EnableScheduling
public class ScheduledUpdatesOnTopic {
Map<Integer, String[]> history = new LinkedHashMap<>();
#Autowired
private SimpMessagingTemplate template;
private Integer count = 0;
#MessageMapping("/topic/history")
#SendTo("/topic/history")
public List<String[]> history(Integer to) {
return history.keySet()
.stream()
.filter(counter -> counter < to)
.map(counter -> history.get(counter))
.collect(Collectors.toList());
}
#Scheduled(fixedRate = 500)
public void sendMessage() {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String[] str = {count.toString(), "name"+count,""+Math.round(Math.random()*100),"India"+Math.round(Math.random()*100),df.format(date)};
history.put(count, str);
this.template.convertAndSend("/topic/message",str);
++count;
}
}
In this sample, saved datas are stored in a map, be aware that it will consume some memory at some point.

Umbraco - MediaPicker Object Data to JSON

In Umbraco 7, is it possible to serialize a mediapicker to json? So it could be something like this....
[{'name':'muffin', 'file':'muffin.jpg', 'text':'some text', 'etc': 'and so on'}]
My setup is like this, I have a mediaPicker named "mediaPhotos". Contained in the folder selected by the mediaPicker I have images of a custom media type "sillyImage".
I can create a controller and query only single items as xml. What I'm trying to target the entire folder of images chosen by the mediapicker and convert its contents to json.
I'm trying to use the solution posted by bowserm below which works like this...
It gets the CurrentPage dynamically with the mediaPicker alias. Then its passed the custom media type.
public class MediaApiController : UmbracoApiController
{
[HttpGet]
public MediaApiModel GetMediaById(string id)
{
var media = Umbraco.TypedMedia(id);
return new MediaApiModel
{
MediaId = media.Id,
MediaUrl = media.Url
};
}
[HttpGet]
public IEnumerable<MediaApiModel> GetMediaObj(string mediaAlias)
{
var currentPage = Umbraco.TypedContent(UmbracoContext.Current.PageId);
var mediaRootId = currentPage.GetPropertyValue<string>("mediaPhotos");
var mediaRoot = Umbraco.TypedMedia(mediaRootId);
var media = mediaRoot.Children.Where(m => m.IsDocumentType(mediaTypeAlias));
return media.Select(m => new MediaApiModel
{
MediaId = m.Id,
MediaUrl = m.Url
});
}
}
var uri3 = '//' + document.domain + ':14712' + '/umbraco/api/MediaApi/GetMediaFolder?mediaAlias=sillyImage';
$(document).ready(function () {
$.getJSON(uri3)
.done(function (data) {
console.log('return json data object ' + data);
});
});
I'm getting a 500 error now so its getting closer. The issue I think is with these lines in the controller
var currentPage = Umbraco.TypedContent(UmbracoContext.Current.PageId);
var mediaRootId = currentPage.GetPropertyValue<string>("mediaPhotos");
var mediaRoot = Umbraco.TypedMedia(mediaRootId);
My pages use a page name so PageId I'm not sure is the root issue. The one item I know is that the GetPropertyValue isn't able to get the media picker object from the current page.
Thanks!
You should be able to get your Api Controller to automatically serialize the results to JSON. Just inherit from UmbracoApiController.
public class MediaApiController : UmbracoApiController
{
[HttpGet]
public MediaApiModel GetMediaById(string id)
{
var media = Umbraco.TypedMedia(id);
return new MediaApiModel
{
MediaId = media.Id,
MediaUrl = media.Url
};
}
[HttpPost]
public IEnumerable<MediaApiModel> GetMediaObj(string mediaTypeAlias)
{
var currentPage = Umbraco.TypedContent(UmbracoContext.Current.PageId);
var mediaRootId = currentPage.GetPropertyValue<string>("mediaPhotos");
var mediaRoot = Umbraco.TypedMedia(mediaRootId);
var media = mediaRoot.Children.Where(m => m.IsDocumentType(mediaTypeAlias));
return media.Select(m => new MediaApiModel
{
MediaId = m.Id,
MediaUrl = m.Url
});
}

View gets Json displayed on the page. not the data

I have an action which returns a JsonResult. The only thing gets displayed on the view is my json which is like
ProcessOrder{"IsValid":true,"url":"/Home/ProcessOrder"}
While debugging the code, I noticed that it gets displayed because of this below line.
var ProcessOrderData = new { IsValid = true, url = Url.Action("ProcessOrder") };
return new JsonResult() { Data = ProcessOrderData };
Can any body please tell me why it gets only json to be displayed on the view?
is something null here that is causing this to get this displayed or any other stuff?
Code:
private ActionResult SubmitAccount(UserAccountModels UserAccountModels)
{
SessionInfo userSession = SiteSetting.Visitor;
if (userSession != null)
{
if (userSession.products.Where(rec => rec.IsAddedToCart).Count() > 0)
{
SiteSetting.Visitor.User.FirstName = UserAccountModels.FirstName;
SiteSetting.Visitor.User.LastName = UserAccountModels.LastName;
SiteSetting.Visitor.User.Phone = UserAccountModels.Phone;
SiteSetting.Visitor.User.Email = UserAccountModels.Email;
var ProcessOrderData = new { IsValid = true, url = Url.Action("ProcessOrder") };
return new JsonResult() { Data = ProcessOrderData };
}}}
It will only display Json because you are returing JsonResult not a View