I am trying to make a jquery ajax call to a static method on the codebehind file. The problem is that ArtistManager injected by Spring is not static and I cannot use it in the static webmethod. I am looking for any ideas on how to implement this
ArtistList.aspx
$(document).ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "ArtistList.aspx/GetArtists",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Result").text(msg.d);
alert("Success: " + msg.d);
},
error: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
alert("Error: " + msg.d);
}
});
});
});
ArtistList.aspx.cs
private IArtistManager artistManager;
public IArtistManager ArtistManager
{
set { this.artistManager = value; }
get { return artistManager; }
}
protected long rowCount = 0;
.
.
.
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
//return ArtistManager.GetAll("Name", "ASC", 1, 100, out rowCount);
}
Assuming a single context, in which an IArtistManager is configured named artistManager:
using Spring.Context.Support;
// ...
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
IApplicationContext context = ContextRegistry.GetContext(); // get the application context
IArtistManager mngr = (IArtistManager)context.GetObject("artistManager"); // get the object
return mngr.GetAll("Name", "ASC", 1, 100, out rowCount);
}
Note that this code won't compile either, since rowCount is an instance member, similar to artistManager in your question.
Don't know about spring, but I am sure it has something like structure map.
ObjectFactory.GetInstance<IAristManager>.GetAll();
Related
I have a problem with my [WebMethod] when I return Json data List<Contract> from DB using Entity Framework
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "/Pages/App/Docs.aspx/PopulateDataByJquery",
data: "{pageNo: " + pageIndex + ", noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
This my WeMethod.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<Contract> PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
return data;
}
I every time getting ajax error, help me please! I don't know how it fix.
You have to make some changes to your ajax call and WebMethod
function populateData(pageIndex) {
// populate data from database
$.ajax({
url: "Docs.aspx/PopulateDataByJquery",
data: "{pageNo: pageIndex, noOfRecord: 7}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: onError
});
}
function OnSuccess(data) {
alert('good');
}
function onError() {
alert('Failed!');
$('#LoadingPanel').css('display', 'none');
}
Change your WebMethod
[WebMethod]
public static string PopulateDataByJquery(int pageNo, int noOfRecord)
{
System.Threading.Thread.Sleep(2000);
Entities4 db = new Entities4();
List<Contract> data = new List<Contract>();
int skip = (pageNo - 1) * noOfRecord;
data = db.Contracts.Include("PhysicalPerson").Include("Product").OrderBy(a => a.Id).Skip(skip).Take(noOfRecord).ToList();
JavaScriptSerializer TheSerializer = new JavaScriptSerializer()
var TheJson = TheSerializer.Serialize(data);
// for this you need to add using System.Web.Script.Serialization;
return TheJson;
}
For more read this
I am creating a web application for event management using .net mvc and jquery.
I created a mvc web app.contoller named SeatPlansController and model named SeatPlanes and I am able to insert the data to database.
But I am not able pass the data from jquery to database using the mvc controller.
My controller action code is as shown below
// GET: SeatPlans/Create
public ActionResult Create()
{
return View();
}
// POST: SeatPlans/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}
In post create controller Id is primary key, so I want to pass seat_id,seat_no as argument and it should update the database.
I used following javascript
function getPerson(id) {
$.ajax({
type: "GET",
url: '#Url.Action("create", "SeatPlanesController")',
contentType: "application/json; charset=utf-8",
data: {eat_id :6, seat_no:8},
dataType: "json",
success: function (result) {
alert(result);
//window.locationre = result.url;
}
});
}
I am able to run the create get method using
http://localhost:52348/SeatPlans/Create
but how can I run post method directly from browser with argument
something like
http://localhost:52348/SeatPlans/Create/2/3t/e
I have changed the script as bellow,it works for GET method but if i made TYPE:"post" it popup an alert box with alert
"localhost:52348 says:
internal server error"
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Create", "SeatPlans", new { Area = "" })',
data: { seat_id: "34", seat_no: "98" },
dataType: "json",
async: false,
success: function (result) {
$("#div1").html(result);
},
error: function (abc) {
alert(abc.statusText);
},
});
});
});
Finally i got the sollution
i changed the script as bellow
//jQuery.noConflict();
// var $j = jQuery.noConflict();
function clickevent()
{
var form = $("#frm");
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "post",
// headers: { "__RequestVerificationToken": token },
url: '#Url.Action("Create", "SeatPlans")',
data: {
seat_id: "34", seat_no: "98"
},
success: function (result) {
$("#div1").html(result);
}
});
}
and change the create post method as bellow
<pre>
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}
Im using Ajax in a .net project (isn't MVC.net). I want to call a function of my .aspx.cs from a JScript Function.
This is my JScript code:
$("a#showQuickSearch").click(function () {
if ($("#quick_search_controls").is(":hidden")) {
$.ajax({
type: "POST",
url: "Default.aspx/SetInfo",
data: "{showQuickSearch}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
}
});
$("#quick_search_controls").slideDown("slow");
$("#search_controls").hide();
$("#search").hide();
} else {
$("#quick_search_controls").hide();
}
});
And this is my .aspx.cs Function:
[WebMethod]
public string SetInfo(string strChangeSession)
{
Label1.Text = strChangeSession;
return "This is a test";
}
The problem is that my .aspx.cs function is not being called and isn't updating the label.text.
Try making your function static.
[WebMethod]
public static string SetInfo(string strChangeSession)
{
//Label1.Text = strChangeSession; this wont work
return "This is a test";
}
data: "{showQuickSearch}" is not valid JSON.
Here's how a valid JSON would look like:
data: JSON.stringify({ strChangeSession: 'showQuickSearch' })
Also your PageMethod needs to be static:
[WebMethod]
public static string SetInfo(string strChangeSession)
{
return "This is a test";
}
which obviously means that you cannot access any page elements such as labels and stuff. It is inside your success callback that you could now use the result of the PageMethod to update some label or whatever.
$.ajax({
type: "POST",
url: "Default.aspx/SetInfo",
data: "{'strChangeSession':'showQuickSearch'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
error: function (xhr, status, error) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message);
}
});
And your backend code:
[WebMethod]
public static string SetInfo(string strChangeSession)
{
return "Response ";
}
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>)
I have a simple webservice in asp.net which determine if the input parameter is valid or not :
[WebMethod]
public bool IsValidNationalCode(string input)
{
return input.IsNationalCode();
}
I call it from an aspx page by jquery ajax function :
$('#txtNationalCode').focusout(function () {
var webMethod = "../PMWebService.asmx/IsValidNationalCode";
var param = $('#txtNationalCode').val();
var parameters = "{input:" + param + "}";
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if(msg.responseText == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
},
error: function () {
$('#status').html("error occured");
}
});
});
But I don't know how to get the return value of webservice in order to show appropriate message . Here if(msg.responseText == true) doesn't work
Make the IsValidNationalCode method static and use this in javascript:
success: function (msg) {
if (msg.d == true)
$('#status').html("Valid");
else {
$('#status').html("Invalid");
}
}
For "d" explanation follow this link: Never worry about ASP.NET AJAX’s .d again