I write a method on my page that return a XMLDocument.This is my method:
[System.Web.Services.WebMethod()]
public static System.Xml.XmlDocument MyGet()
{
string cnn=System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.ToString();
SqlConnection cn = new SqlConnection(cnn);
SqlCommand cmd = new SqlCommand("select * from region", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cn.Open();
DataSet dt = new DataSet();
da.Fill(dt);
XmlDocument xdoc=new XmlDocument();
xdoc.LoadXml(dt.GetXml());
return xdoc;
}
and this is my jQuery Ajax code:
$.ajax({
type: "POST",
url: "Default2.aspx/MyGet",
data: "{}",
dataType: "xml",
success: function(result) {
$(result).find("Table").each(function() {
alert($(this).find("RegionID").text());
});
}
but it does not work.
If I write MyGet method in Web Service it works very fine.
where is the problem?
thanks alot
Try adding the following attribute to your service operation:
[ScriptMethod(ResponseFormat=ResponseFormat.Xml)]
I suggest you get rid of the {} in your data parameter. It's likely that the serializer thinks you want json back, not xml.
My suggestion is that try Jquery plugins that converts xml to json. Your problem is with Jquery api not with asp.net.
A few suggestions:
1) Shouldn't the "{}" be without quotes?
2) You could try alert(response); inside your success function to see what kind of data jQuery thinks it has. It could be text.. I've had unexpected data types before with jQuery.
3) You could try $("Table", result) instead of $(result).find("Table")
Hope this helps
Related
Please help.
I have 3 dropdowns :
1. Country
2. Port
3. Company Name
Once 1st dropdown (countries) is selected, 2nd dropdown should be populated with a list of specific ports, then based on 1st and 2nd dropdown, the 3rd dropdown will be populated also.
this is a one time key-in. Meaning once selection is done, the user will save it in db and the value should remain in the dropdown unless the user change.
Right now, i'm using OnSelectedIndexChanged which is very slow because of the postback.
let me know if there's any other way of doing.
Thanks,
Jack
there could have several ways to achieve this. One of the ways is using WebService [WebMethod]. Ajax and JSON.
//You databinding method must be public and add [WebMethod] attribute
[WebMethod]
public static List<ListItem> GetCustomers()
{
string query = "SELECT CustId, CustName FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
List<ListItem> custListItem = new List<ListItem>();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
custListItem.Add(new ListItem
{
Value = Convert.ToString(sdr["CustId"]),
Text = Convert.ToString(sdr["CustName"])
});
}
}
con.Close();
return custListItem;
}
}
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "CustomerList.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var ddlCustomers = $("[id*=ddlCustomers]");
ddlCustomers.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(r.d, function () {
ddlCustomers.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
});
});
</script>
You basically have 2 options, preload your values into a js structure (counties, ports and companies), or use a ajax/xmlhttprequest call to load just the relevant information (just the ports for a specific country). If preloading the values, you can either mix it in with your html in the body of a script tag, or have it be a seperate file that is loaded via a src attribute.
Which is best to use will vary based upon your user base and data size, and how frequently the data changes.
Sorry Im new to this approach.
I wanted to write various web servers at my sql server using .net c#.
to perform various operations to my database, e.g update customer, delete customer, select customer etc..
I am writing a client side web app (to deploy eventually on a mobile) that will send and retrieve data to these web services.
I am unsure of the methods that allow me to do this from my client that allow authentication and are reasonably secure.
So far I am thinking of Jquery AJAX?
Ajax will allow you to exchange data between server and client within a page without reloading it. It sends and receives data using HTTP messages.
Setup REST service and add jQuery to HTML page. At this point you have a communication channel. Now you have to think about security model.
You may require client to send username+password or authentication token in every request. You also may place these credentials anywhere within HTTP message (cookie, header, body).
If it's your first experience with ASP.NET, try to use standard Forms Authentication (it stores authentication token in ASPX_AUTH cookie) or any .NET builtin authentication models.
See articles below to see examples:
Security in ASP.NET
Secure a Web API with Individual Accounts and Local Login in ASP.NET Web API 2.2
first Create ASMX File
second Create Class inside or outside the ASMX File
public class NationalityInfo
{
public int ID { get; set; }
public string Name { get; set; }// any Other
}
[WebMethod]
[ScriptMethod]
public List<NationalityInfo> LoadNat()
{
string Conn = System.Configuration.ConfigurationManager.ConnectionStrings["GPS_TrackingConnectionString"].ConnectionString;
List<NationalityInfo> NatInformation = new List<NationalityInfo>();
DataSet ds;
using (SqlConnection con = new SqlConnection(Conn))
{
using (SqlCommand cmd = new SqlCommand("select * from Nationality", con))
{
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
ds = new DataSet();
da.Fill(ds);
}
}
}
try
{
if (ds != null)
{
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
NatInformation.Add(new NationalityInfo()
{
ID = Convert.ToInt32(dr["Id"]),
Name = dr["Name"].ToString()
});
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return NatInformation;
}
in the client side
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Query.asmx/LoadNat",
data: "{}",
dataType: "json",
success: function (Result) {
Result = Result.d;
$.each(Result, function (key, value) {
var id=value.ID;
var Name=value.Name;
});
},
error: function (Result) {
}
});
Note in the client side you get object (Array ) not json
For saving (Get values from client to server)
function SaveNat() {
var Nat = {};
Nat.ID = txtID.value;
Nat.Name = txtName.value;
var NatVar = JSON.stringify(Nat);
$.ajax({
type: "POST",
url: "Query.asmx/SaveNat",
data: '{Nat: ' + NatVar + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert('Saved');
}
});
}
Server Save Function
[WebMethod(EnableSession = true)]
[ScriptMethod]
public void SaveNat(NationalityInfo Nat)
{
string Conn = ""// Your Connection
using (SqlConnection con = new SqlConnection(Conn))
{
using (SqlCommand cmd = new SqlCommand())
{
//Save }
}
}
as for security you must not sent user name and passwor in plain text it will be visible in the Browser trafic
you should send it encrypted and decrypt it on your server
I've been trying to find an answer on google without any result. My question is how can I manipulate my Json data (List<string>) in my view? I'd like to show all the string returned in a div for example.
Here's where I'm currently stuck at:
CONTROLLER
[HttpPost]
public async Task<ActionResult> RetournerOP(int OF)
{
List<string> ops = new List<string>();
Task verif = Task.Run(() =>
{
try
{
connection.Open();
string sqlQuery = "SELECT Operation from ZZ where ordre = " + OF;
SqlCommand command = new SqlCommand(sqlQuery, connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ops.Add(Convert.ToString(reader["Operation"]));
}
}
}
catch (Exception) { }
finally { connection.Close(); }
});
await verif;
return Json(ops);
}
VIEW
function retournerOp() {
$.ajax({
url: '#Url.Action("RetournerOp", "Home", new { area = "Ajout" })',
data: {OF: document.getElementById("NumOf").value},
type: 'POST',
dataType: 'JSON',
cache: false,
success: function (data) {
//How can I manipulate my data returned?
}
});
}
Your server action method is currently returning an array of strings. So in your ajax call's success callback, you may loop through them and use each item as needed ( like adding to your DOM). $.each method will be handy to loop.
For example, the below code loops through the array and wrap each item in a p tag and append the list of p tags to a div with id myDivId
success: function (data) {
var t = "<div>";
$.each(data,function(a, b) {
t += '<p>'+b+'</p>';
});
$("#myDivId").html(t);
}
If you want to render a more complex html markup, i would strongly advise creating an action method (if you cannot update the existing one because other code is already using it) which returns a partial view result instead of the json. So you will pass the list of strings to the partia view and the partial view will have the code to render the sophisticated markup you want to return.
return PartialView(ops);
and in the partial view,
#model List<string>
#foreach (var item in Model)
{
<p>#item</p>
}
Now since the response coming from the server call is the HTML markup you want, simply update the DOM with that as needed.
$.ajax({
url: '#Url.Action("RetournerOp", "Home", new { area = "Ajout" })',
data: {OF:6},
type: 'POST',
success: function (data) {
$("#myDivId").html(data);
}
});
Also as others mentioned in the comments, your server code is prone to SQL injection. You should never concatenate the user input directly to a SQL statement like that. Consider using Parameterized queries.
I have written a webservice call in JQuery in document ready function but its not calling the function
Below is the code
JQuery
`<script type="text/javascript">
$( document ).ready(function() {
var section = "Table - TLI (STOCK)";
$.ajax({
type: "GET",contentType: "application/json; charset=utf-8",
url: "pgWebService.aspx/SliderBlock",
dataType: "json",
data: "{'section':'" + section + "'}",
success: function (res) {
//$("#Text1").val(res.text);
console.log(res);
alert("DONE");
}
});
});
</script>`
C# Code
pgWebService
public static string SliderBlock(string section)
{
string html = "<ul class='maketabs listing-table search-filter change-view'>";
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["TLI"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd.Connection = cn;
cmd.CommandText = "Select * from CategoryDetails where section=" + section;
SqlDataReader rs = cmd.ExecuteReader();
while (rs.Read())
{
html="<li>"+rs.getValue(0).toString()+"</li>";
}
rs.Close();
cmd.Dispose();
cn.Close();
html = html + "</ul>";
return html;
}
If your method SliderBlock is in code behind than make your method WebMethod to be called by ajax.Also you need to make it static and to be called by GET you need to enable GET requests on your WebMethod.
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static string SliderBlock(string section)
{
//Your code here
}
As your code has the extension .aspx I assume that you are using the code-behind ( Page Method ). So you need to make these changes to your function signature
[System.Web.Services.WebMethod]
public static string SliderBlock(string section)
That is,
your method should be static.
your method should be decorated with System.Web.Services.WebMethod
And in your $.ajax call, change the dataType to json.
dataType: "json"
Also, please bear in mind that the PageMethid in pgWebService.aspx.cs can be only called from pgWebService.aspx
You still have errors in the ajax request:
Content-Type: When sending data to the server, use this content type. But you are not sending data to the server except the query string parameters because you are doing a GET. So, if you inspect with webbrowser developer tools the request you see a GET with this URL: localhost/pgWebService.aspx/SliderBlock?section=selectedSection because...
Data: Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests.
dataType: The type of data that you're expecting back from the server. But in your webService your are returning a string with HTML not JSON.
Hopefully this is a fairly easy question. Pardon my ignorance, but I am mostly a PHP/Zend developer, so i am struggling a little in C# and Visual Studio with a json/ajax issue. Is there something obvious I am missing? Any help will be appreciated. Should I be looking at List<>?
Here is the error I receive when I fire the javascript ajax function:
"Unknown web method getwidgets."
I have a dataset in C#, that I run through a JSON converter method. This works well and returns my data in a JSON string.
private widgetsBL widgetsBLObject = new widgetsBL();
[WebMethod]
public String getwidgets()
{
DataSet results = new DataSet();
results = widgetsBLObject.selectTheWidgets();
string jsresults = MyClassLibrary.JqueryTools.GetJSONString(results.Tables[0]);
return jsresults;
}
Here is the jsresults:
{"Table" : [ {"widgetid" : "1","widgetname" : "gizmo1000","widgetdescription" : "very cool widget"},
{"widgetid" : "2","widgetname" : "gizmo2000","widgetdescription" : "decent widget"},
{"widgetid" : "3","widgetname" : "gizmo3000","widgetdescription" : "terrible widget"} ]}
My Javascript call:
$.ajax({
type: "POST",
url: "my.aspx/getwidgets",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// do stuff with returned data
}
});
getwidgets needs to be static
[WebMethod]
public static String getwidgets()
Remember that if you want your method to be exposed to calls from JavaScript, you need to mark your method with ScriptMethodAttribute. Thus making it look like this:
[ScriptMethod]
[WebMethod]
public static String getwidgets()
{
// Your core here
}
I would return in the method, the object itself and not not a serialized version of it because ASP.NET will JSON serialize it for you if you mark it as [ScriptMethod]; so in the client your variable data.d will contain the object itself and not a simple string that later you have to deserialize, as in your current implementation.
You are mixing technologies: my.aspx is for rendering HTML content, but it can be used to implement REST functionality.
In your case, the easiest would be to implement your code as part of the Page_Loaded() method. Make sure you clear the response first (so you don't have any additional markup in the response). Furthermore, you might want to set the content type of your response to JSON (rather than the default html):
protected void Page_Load(object sender, EventArgs e)
{
Response.ClearContent();
Response.ContentType = "application/json";
DataSet results = new DataSet();
results = widgetsBLObject.selectTheWidgets();
string jsresults = MyClassLibrary.JqueryTools.GetJSONString(results.Tables[0]);
return jsresults;
}
Then retrieve you JSON string at my.aspx (no getwidgets).
Also, since you are not posting any data, consider using GET rather than POST in your AJAX call.