I am trying to call the following C# method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getJSONdata()
{
string jsonString = "";
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<Dot> _Dot = new List<Dot>();
while (reader.Read())
{
Dot dot = new Dot();
dot.x = (int.Parse(reader["xCoord"].ToString()));
dot.y = (int.Parse(reader["yCoord"].ToString()));
if (reader["DrawID"] != DBNull.Value)
dot.i = (int.Parse(reader["DrawID"].ToString()));
_Dot.Add(dot);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
jsonString = jss.Serialize(_Dot);
}
}
}
System.Diagnostics.Debug.WriteLine(" JSON: " + jsonString);
return jsonString;
}
Here is my JavaScript code:
$.ajax({
url: 'Default.aspx/getJSONdata',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
First, I am getting the ajax error. No idea why it's not called.
Second, I am still not sure I am returning the correct JSON data I want, whether in the correct format or not. Thanks for your help.
Edit. It is returning a JSON string correctly.
Note: the connectionString works in another function, so that's not it.
Download and install Fidder4.
This will allow you to see the traffic between your page and your server. You can see the actual call URL and then paste it into a browser to see what it returns. This will give you a tool to solve this type of problem going forward.
Related
I ran into a problem with Ajax: i am calling a server side function via Ajax. Nothing strange so far. The problem is that it doesn't give me back any results and while debugging, I found that it gives permission problems. I don't understand where the problem is.
CODICE AJAX
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
let parametri = { utente: user, Password: pass }
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebControls.aspx/CliccaBottone",
data: JSON.stringify(parametri),
dataType: "json",
success: function (i) {
if (i == 0) {
alert("Le credenziali sono errate");
}
else {
alert("Hai eseguito il login");
}
}
});
CODICE C#
public partial class WebControls : System.Web.UI.Page
{
[WebMethod(EnableSession = true)]
public static int CliccaBottone(string utente, string Password)
{
string queryString = "SELECT * FROM Credenziali WHERE Username = #User AND Pass = #Password";
int i = 0;
//VIENE APERTA LA CONNESSIONE COL DB
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["coso"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
SqlParameter parameter = new SqlParameter("User", utente);
SqlParameter parameter2 = new SqlParameter("Password", Password);
command.Parameters.Add(parameter);
command.Parameters.Add(parameter2);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
i++;
}
reader.Close();
}
}
return i;
}
}
}
I suspect there is an error on the server side, because the syntax written on the client side seems correct to me. But logically if an incorrect function is called that will not work. Thank you very much for helping.
How are you handling credentials when connecting the the database itself? If it's pass through authentication, what credentials is your application using when accessing the database?
I have a C# method that works if you call it from another C# method, but not from javascript. How do I make it work from my ajax call?
I need to get a file based on an ID that is passed in, so I have an ajax post with the statusID. That ID is pulling the proper file in my C# method, it is just not giving the file save dialog.
However, if I call this from my C# page load method with a static statusID for testing purposes, it works just fine.
Here is the C# method:
public void Get_Attachment_By_StatusID(int statusID)
{
SqlDataReader _reader = null;
string _connString = "Data Source=133.31.32.33;Initial Catalog=Reports;Integrated Security=True";
string sql = "SELECT a.StatusID ,a.DocumentName ,a.MIMETypeID ,a.Binary ,a.CreatedDate ,a.CreatedBy " +
",b.MIMEType FROM Attachments a Inner join MIME_Types b on a.MIMETypeID = b.ID " +
"WHERE [StatusID] = {0} ";
sql = string.Format(sql, statusID);
try
{
_connection = new SqlConnection(_connString);
_connection.Open();
using (SqlCommand cmd = new SqlCommand(sql, _connection))
{
cmd.CommandType = System.Data.CommandType.Text;
_reader = cmd.ExecuteReader();
if (_reader.HasRows)
{
while (_reader.Read())
{
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.ContentType = _reader["MIMEType"].ToString();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + _reader["DocumentName"].ToString() + ";");
byte[] b = (byte[])_reader["Binary"];
System.Web.HttpContext.Current.Response.BinaryWrite(b);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
}
_reader.Close();
_connection.Close();
}
}
catch (Exception ex)
{
//Log exception to error Logging app
string err = ex.ToString();
}
finally
{
if (_connection != null)
_connection.Close();
if (_reader != null)
_reader.Close();
}
}
Here is how I am calling it from my page, in javascript:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID';
$.ajax({
url: url,
type: 'post',
cache: false,
data: JSON.stringify({ "statusID": statusID }),
contentType: 'application/json',
success: function (data) {
}
});
}
Nothing happens. In Chrome, I don't see anything in the javascript console, and in IE, my console spits this out: "XML5619: Incorrect document syntax."
Again, if I go into the controller, and call the method in my page load method, it presents the save file dialog and saves the file just fine. So I must be doing something wrong with my javascript/jquery/ajax...
I am new to MVC4 and know I'm missing something here. What am I missing?
Use window.open('CONTROLLER_URL/STATUS_ID'); instead of an AJAX request.
<a target="_blank" href="javascript:window.open('/Home/Get_Attachment_By_StatusID/12345');">Test</a>
Here's one suggestion, largely based on answer from LastCoder:
Decorate your action with the [HttpGet] attribute and change the parameter name to id:
[HttpGet]
public void Get_Attachment_By_StatusID(int id) ...
Now in your client-side code, simply do this:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID/'+statusID;
window.location=url;
}
how to pass the value in below script to the server side
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
FB.api('/me', function(me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('Email').innerHTML = me.email;
document.getElementById('gender').innerHTML = me.gender;
document.getElementById('birth').innerHTML = me.birthday;
document.getElementById('firstname').innerHTML = me.first_name;
})
Javascript variables exist on the client so in order to get those values into the server you'll need to execute a request from the client.You probably want an approach called AJAX. AJAX involves Javascript making requests to the server in the background of your page. You'll set up a C# web page that expects these background requests. If you use a GET request then then place the variables in the query string of your AJAX request to your new C# page. If you want to use a POST request then you'll set parameters in the data that you post to your page.
Libraries like jQuery make this kind of thing pretty simple.
In webform2.aspx
<script type="text/javascript">
function LoadValues(me) {
{
var Email = me.email;
var Name = me.name;
var Id = me.id;
var Dob = me.birthday;
var Gender = me.gender;
alert(Email)
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
var data2Send = '{"fbemail": '+Email+', "fbname":'+Name+', "fbid":'+Id+',"fbname":'+Dob+',"fbname":'+Name+' }';
$.ajax({
type: "POST",
url: 'webform2.aspx/Testmethod',
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) {console.log(arg) //call successfull
$("#lbltxt").text(arg);
},
error: function (xhr) {
alert(xhr); //error occurred
}
});
}
</script>
In webform2.aspx.cs
[System.Web.Services.WebMethod]
public static string TestMethod(string fbid, string fbemail, string fbsex, string fbdob)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataReader datareader;
con = new SqlConnection(".......");
cmd = new SqlCommand("SpFacebookInfo", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FbId", fbid);
cmd.Parameters.AddWithValue("#FbEmail", fbemail);
cmd.Parameters.AddWithValue("#FbSex", fbsex);
cmd.Parameters.AddWithValue("#FbDob", fbdob);
datareader = cmd.ExecuteReader();
datareader.Close();
return fbemail;
}
}
Set the value in a hidden variable as u did and do a document.myform.submit();
to go to Page_Load and read the variables
I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}
So I'm running GetServerUpdateProgress() in the controller from a $.ajax call on my page. While debugging I can confirm that the variable: myobj is being properly created and filled with the correct data.
But when on the $.ajax success, I'm not getting the data in json format, instead I'm getting
a string of "TrackerMVC.ClassLib.UpdateAJAXProgress" - the objects type.
I've done this in the past with a .svc webservice and didn't have any problems getting the object values using this exact same method.
Any ideas? Thanks!
method:
public UpdateAJAXProgress GetServerUpdateProgress()
{
string BASE_URL = "http://localhost:55094";
string url = BASE_URL + "/Home/UpdateProgress";
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultNetworkCredentials; // uses current windows user
var myojb = new UpdateAJAXProgress();
var response = (HttpWebResponse)wr.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
myojb = (UpdateAJAXProgress)js.Deserialize(objText, typeof(UpdateAJAXProgress));
return myojb; // during debugging this object has the correct values in the correct format
}
class:
public class UpdateAJAXProgress
{
public int Completed { get; set; }
public int Total { get; set; }
}
javascript:
$.ajax({
type: "POST",
async: false,
url: '#(Url.Action("GetServerUpdateProgress","Charts"))',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data); // data being returned is: "TrackerMVC.ClassLib.UpdateAJAXProgress"
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.responseText);
}
});
You're misusing MVC.
You should declare your function as returning ActionResult, then return Json(myobj).
If you return a non-ActionResult from an MVC action, MVC will convert it to a string by calling ToString().