Fetch data from asp.net using backbone - asp.net

$.ajax({
type: "POST",
url: "Home.aspx/loadSB",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
for (i = 0; i < msg.d.length; i++) {
$('#sidebar ul').append('<li class="inactive"><a>' + msg.d[i].Title + ' </a></li>');
}
}
});
I go through this
https://github.com/kjbekkelund/writings/blob/master/published/understanding-backbone.md
and
https://gist.github.com/ryandotsmith/1655019
tutorial and create a backbone as below, but is not working well as the model did not fetch data from asp.net, which part goes wrong? I still new to backbone
Menu = Backbone.Model.extend({
parse: function (data) { return data; }
});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
parse: function (response) { return response.rows; }
});
MenuView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', this.appendMenu, this);
},
appendMenu: function (msg) {
for (i = 0; i < msg.d.length; i++) {
this.$('ul').append('<li class="inactive"><a>' + msg.d[i].Title + ' </a></li>');
}
}
});
var mc = new MenuCol();
//mc.fetch();
//Update1:
new MenuView({ el: $('#sidebar'), collection: mc });
Update 1:
I had play around with fetch, but still not working well,
Menu = Backbone.Model.extend({});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
});
var test = new MenuCol();
test.fetch();
It did not return the data that I want, instead of, it display the interface that my screen have
If i using the jquery.ajax without backbone, it return the json data to me, which part goes wrong? Any guide will be great
Update 2:
Ok, I had change the "fetch", and now I able to see the json data passing into backbone
var test = new MenuCol();
test.fetch({ type: 'POST', contentType: "application/json; charset=UTF-8" });

Ok, finally I had solved the problem,
define(['jquery', 'underscore', 'backbone'], function () {
Menu = Backbone.Model.extend({});
MenuCol = Backbone.Collection.extend({
model: Menu,
url: "Home.aspx/loadSB",
});
MenuView = Backbone.View.extend({
initialize: function () {
this.collection.on('add', _.bind(this.AppendMenu, this));
},
AppendMenu: function (msg) {
var feed = JSON.parse(JSON.stringify(msg));
for (var i = 0; i < feed.d.length; i++) {
this.$('ul').append('<li class="inactive"><a>' + feed.d[i].Title + ' </a></li>');
}
}
});
var test = new MenuCol();
test.fetch({ type: 'POST', contentType: "application/json; charset=UTF-8" });
new MenuView({ el: $('#sidebar'), collection: test })
});
by changing the fetch type to "POST" and contentType: "application/json; charset=UTF-8", finally i manage to populate web with the data I want

Related

put the word "Please Wait, Don't Close The Windows" on Ajax Loading

I am using partial view for my projects.
My Ajax Code is Here :
$("#btnAdd").on("click", function () {
var formData = new FormData();
var dhnFiles = $("#fileDHN")[0].files;
if (dhnFiles.length == 0) {
alert("Pilih file DHN terlebih dahulu!");
return;
}
for (var i = 0; i < dhnFiles.length; i++) {
formData.append("DataDHN", dhnFiles[i]);
}
$.ajax({
method: "POST",
url: "#Url.Action("PartialViewTableDataDHN")",
data: formData,
contentType: false,
processData: false
}).done(function (data) {
$("#TableDHN").html(data);
}).fail(function () {
alert("Error submitting data to server.");
});
});
The loading about 20minutes. and I want the user wait and don't close the windows.
How do i add the words 'Please wait, don't close the windows' while loading.
Thank you.
you can perhaps add a overlay div which you can show using the beforeSend pre-request callbak... then you can hide the ovelay message when ajax is completed...
$.ajax({
method: "POST",
url: "#Url.Action("PartialViewTableDataDHN")",
data: formData,
contentType: false,
processData: false,
beforeSend: function( xhr ) {
$('#overlay_message').show();
}
}).done(function (data) {
$("#TableDHN").html(data);
}).fail(function () {
alert("Error submitting data to server.");
}).completed(function(){
$('#overlay_message').hide();
});
See how to create an overlay: https://www.w3schools.com/howto/howto_css_overlay.asp

formdata in ajax call

When I pass formdata in ajax call after json return it does not return on Success or error block just printing value on browser
// And my Controller side code is
[HttpPost]
public JsonResult Create(InquiryModel model)
{
var inquiry = _inquiryService.GetInquiryById(model.Id);
return Json(inquiry.Id, JsonRequestBehavior.AllowGet);
}
// View side
var formData = new FormData();
jQuery.each(jQuery('#QuotationDocument')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
contentType: false,
processData: false,
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});
when I pass only formData it works fine
Try like this;
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
datatype: "json",
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});

angularjs repeat does not show data at first time

First, I am so sorry because of my English.
I am showing a table that it's data come from server and shown with angular repeat.
I make a ng-click on each row of table that send an ajax request and get another list that I want to show in another table, until now all the thing are right,
but I have a little problem, my problem is that I must click twice on my first table's row to show second table data, at first time all the data comes from server but did not show in second table, my angular code is shown below.
angular.module("BI", [])
.controller("ListTables", function ($scope, $http) {
$scope.ReportLst = [];
$scope.myData = {};
$scope.myData.ReportLst = [];
$scope.myData.ReportDetail = [];
$scope.myData.ReportDetail2 = [];
$scope.selectedReportval = "";
$scope.Load = function () {
$http.post('MakeReport.aspx/LoadReportLst', { data: {} })
.success(function (data) {
$scope.myData.ReportLst = JSON.parse(data.d);
})
.error(function (data, status) {
alert('error');
});
}
$scope.SelectRepID = function (val) {
$.ajax({
type: "POST",
url: "MakeReport.aspx/GetReportDetail",
contentType: "application/json; charset=utf-8",
data: "{ 'val': '" + val + "'}",
dataType: "json",
success: function (data) {
$scope.myData.ReportDetail = JSON.parse(data.d);
},
error: function (data, status, jqXHR) {
alert(data.d);
}
});
$scope.selectedReportval = val;
}
});
In your second request you're using $.ajax instead of $http, because this isn't an Angular function a digest won't be triggered and your view won't be updated, in order to fix this you have to use $http there too.
$scope.SelectRepID = function (val) {
$http.post({
url: "MakeReport.aspx/GetReportDetail",
contentType: "application/json; charset=utf-8",
data: "{ 'val': '" + val + "'}",
dataType: "json"
}).then(
function(data) {
$scope.myData.ReportDetail = JSON.parse(data.d);
}, function(error) {
alert(error);
}
);
$scope.selectedReportval = val;
}
Update: Another way would be to use a $timeout in your $.ajax success function like so (this will trigger a digest).
success: function (data) {
$timeout(function() {
$scope.myData.ReportDetail = JSON.parse(data.d);
});
}

Return JSON List and use on MVC 4 View Page

I have used JSON to return a list but unsure how to use the returned list on a MVC 4 view page. Is this possible?
View Page
var subjectId = value;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/JobProfiles/FindJobProfiles/" + subjectId,
data: "{}",
dataType: "json",
success: function (data)
{
}
});
Controller
[HttpPost]
public ActionResult FindJobProfiles(int? subjectId)
{
if (subjectId.HasValue)
{
Subject subject = subjectRepository.Get(subjectId.Value);
IList<JobProfile> jobProfiles = jobProfileRepository.GetBySubject(subject.Id, false, false);
var jobProfileList = from c in jobProfiles select new { Id = c.Id, Title = c.Title };
return new JsonResult { Data = jobProfileList.ToList() };
}
else
{
return null;
}
}
View Page Display
foreach (JobProfile job in jobProfiles)
{
<a href="/JobProfiles/View/#job.Id" title="#job.Title">#job.Title
}
The correct data is returned but not sure how to access the list on the view page and display the data.
Add a div to the page for the result or the html element you would like to display it:
<div id="results" />
Add a success handler that loops the result and appends it:
var subjectId = value;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/JobProfiles/FindJobProfiles/" + subjectId,
data: "{}",
dataType: "json",
success: function(data) {
$.each(data, function(index, item) {
$('#results').append('<a href"/JobProfiles/View/' + item.Id + '" title="' + item.Title +'">' + item.Title + '</a>');
});
}
});
I assuming, you want to display data in list.
For that you need to have div with some id say target-div in your html page.
Using jquery you can display list in target-div as shown below.
success: function (data){
var markup='<ul>';
for (var i = 0; i < data.length; i++)
{
markup+='<li>'+ data[i].itemName +'<li>';
//itemName is key here.
}
markup+='</ul>';
$('#target-div').html(markup);//this will place the list in div.
}

pass an array in jquery via ajax to a c# webmethod

I'd like to pass an array to a c# webmethod but don't have a good example to follow. Thanks for any assistance.
Here is what I have so far:
My array:
$(".jobRole").each(function (index) {
var jobRoleIndex = index;
var jobRoleID = $(this).attr('id');
var jobRoleName = $(this).text();
var roleInfo = {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
};
queryStr = { "roleInfo": roleInfo };
jobRoleArray.push(queryStr);
});
My ajax code
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: jobRoleArray,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
Not sure on the webmethod but here is what I'm thinking:
[WebMethod]
public static bool save_Role(String jobRoleArray[])
You will be passing an array of:
[
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
},
"roleInfo": {
"roleIndex": jobRoleIndex,
"roleID": jobRoleID,
"roleName": jobRoleName
}, ...
]
And in my opinion, it would be easier if you have a class that matches that structure, like this:
public class roleInfo
{
public int roleIndex{get;set;}
public int roleID{get;set;}
public string roleName{get;set;}
}
So that when you call your web method from jQuery, you can do it like this:
$.ajax({
type: "POST",
url: "WebPage.aspx/save_Role",
data: "{'jobRoleArray':"+JSON.stringify(jobRoleArray)+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
alert("successfully posted data");
},
error: function (data) {
alert("failed posted data");
alert(postData);
}
});
And in your web method, you can receive List<roleInfo> in this way:
[WebMethod]
public static bool save_Role(List<roleInfo> jobRoleArray)
{
}
If you try this, please let me know. Above code was not tested in any way so there might be errors but I think this is a good and very clean approach.
I have implement something like this before which is passing an array to web method. Hope this will get you some ideas in solving your problem. My javascript code is as below:-
function PostAccountLists() {
var accountLists = new Array();
$("#participantLists input[id*='chkPresents']:checked").each(function () {
accountLists.push($(this).val());
});
var instanceId = $('#<%= hfInstanceId.ClientID %>').val();
$.ajax({
type: "POST",
url: "/_layouts/TrainingAdministration/SubscriberLists.aspx/SignOff",
data: "{'participantLists': '" + accountLists + "', insId : '" + instanceId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
}
In the code behind page (the web method)
[WebMethod]
public static void SignOff(object participantLists, string insId)
{
//subscription row id's
string[] a = participantLists.ToString().Split(',');
List<int> subIds = a.Select(x => int.Parse(x)).ToList<int>();
int instanceId = Convert.ToInt32(insId);
The thing to notice here is in the web method, the parameters that will receive the array from the ajax call is of type object.
Hope this helps.
EDIT:-
according to your web method, you are expecting a value of type boolean. Here how to get it when the ajax call is success
function AjaxSucceeded(result) {
var res = result.d;
if (res != null && res === true) {
alert("succesfully posted data");
}
}
Hope this helps
Adding this for the ones, like MdeVera, that looking for clean way to send array as parameter. You can find the answer in Icarus answer. I just wanted to make it clear:
JSON.stringify(<your array cames here>)
for example, if you would like to call a web page with array as parameter you can use the following approach:
"<URL>?<Parameter name>=" + JSON.stringify(<your array>)

Resources