I trying to pass JSON from jQuery to .ASHX file.
I want retrieve JSON data in .ASHX file by HttpContext and cats to NameValueCollection.
How do it?
$.ajax({
url: "GetLetterInformationHandler.ashx",
data: "{'Name':'david', 'Family':'logan'}",
contentType: "application/json; charset=utf-8",
type: "Get",
datatype: "json",
onSuccess: function (data) {
}
});
Now I can use the querystring and And cast as follows:
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
string cururl = context.Request.Url.ToString();
int iqs = context.Request.Url.ToString().IndexOf('?');
string querystring = (iqs < cururl.Length - 1) ? cururl.Substring(iqs + 1) : String.Empty;
NameValueCollection parameters = HttpUtility.ParseQueryString(querystring);
context.Response.ContentType = "text/plain";
}
I want use json insted of querystring
Try this:
$.map(data.d, function (item) {
return {
name: item.Name,
family: item.Family
};
})
Or if you want each function:
var resultData = data.d;
$.each(resultData, function() {
alert(this)
})
I have made some changes hope this will help you :)
Ajax function
$.ajax({
type: "POST",
url: "GetLetterInformationHandler.ashx",
data: "{'Name':'david', 'Family':'logan'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if( data != null){
if (data.msg == "SUCCESS"); {
alert( data.msg)
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
.ASHX file
public void ProcessRequest(HttpContext context)
{
string outputToReturn = String.Empty; // Set it to Empty Instead of ""
context.Response.ContentType = "text/json";
var getName = String.Empty ;
var getFamily = String.Empty ; // Make sure if the Particular Object is Empty or not
if (!string.IsNullOrEmpty(context.Request["Name"]))
{
getName = context.Request["Name"];
}
if (!string.IsNullOrEmpty(context.Request["Subject"]))
{
getFamily = context.Request["Subject"];
}
NameValueCollection nvc = new NameValueCollection();
nvc.Add(getName, getFamily);
var dict = new Dictionary<string, string>();
foreach (string key in nvc.Keys)
{
dict.Add(key, nvc[key]);
}
string json = new JavaScriptSerializer().Serialize(dict);
Console.WriteLine(json);
}
Related
In my webForm project as follow :
I have a button which user click on it
call a web method (via jquery request) to extract some binary data from sql server as pdf
Then give a user to download/view the pdf via browser.
This works for my development machine. However, this fails on production server and give to user an empty pdf!
Where is my problem & how to solve it?
Here is jquery request to my web method :
function OpenAttachment(jsonData){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MedicalHistory.aspx/OpenAttachment",
data: JSON.stringify({ objData: jsonData }),
dataType: "json",
success: function (response) {
gdv.PerformCallback('downloadfile|' + response.d);
},
error: function (request, status, error) {
alert('error : ' + error);
}
});
}
Here is my web method :
[WebMethod]
public static string OpenAttachment(object objData)
{
string strResult = string.Empty;
if (objData == null)
return strResult;
DataTable dtResult = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(objData.ToString());
string strDocContent = dtResult.Rows[0]["DocContent"].ToString();
string strFileName = dtResult.Rows[0]["FileName"].ToString();
byte[] pdfByteArray = Encoding.Default.GetBytes(strDocContent);
HttpContext.Current.Session["_binDownloadData"] = pdfByteArray;
strResult = strFileName;
return strResult;
}
And here is download code in my download page :
object objDownloadData = Session["_binDownloadData"];
if (objDownloadData != null)
{
byte[] pdfByteArray = (byte[])objDownloadData;
string strContentType = string.Empty;
if (strFileType == "pdf")
{
strContentType = "application/pdf";
}
#region Downloading file
HttpContext.Current.Response.Clear();
MemoryStream ms = new MemoryStream(pdfByteArray);
HttpContext.Current.Response.ContentType = strContentType;
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", strFileName));
HttpContext.Current.Response.Buffer = true;
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
#endregion
Session["_binDownloadData"] = null;
}
Thanks in advance.
Try with changing contentType and dataType.
$.ajax - dataType
function OpenAttachment(jsonData){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MedicalHistory.aspx/OpenAttachment",
data: JSON.stringify({ objData: jsonData }),
dataType: "application/pdf",
success: function (response) {
gdv.PerformCallback('downloadfile|' + response.d);
},
error: function (request, status, error) {
alert('error : ' + error);
}
});
}
I want to pass array value to my web service file. But it throws the following error
setDeleteFiles
Test
The test form is only available for methods with primitive types as parameters.
Here is my jquery code
$('#btnDeleteFiles').click(function () {
var filesPaths = [];
i = 0;
$("input:checkbox[name=filed-checkedbox]:checked").each(function () {
filesPaths[i] = $(this).val();
i++;
});
//alert("filesPaths = " + filesPaths)
var location = $('#ddlLocation option:selected').text();
alert("Location = "+location)
$.ajax({
method: 'post',
url: "GetAllFolderDetails.asmx/setDeleteFiles",
data: {
location: location,
fileNames: filesPaths
},
dataType: "json",
success: function (data) {
window.location.reload(true);
//alert("Success");
},
error: function (result) {
alert("Error");
}
});
});
GetAllFolderDetails.asmx code
[WebMethod]
public void setDeleteFiles(string location, string[] fileNames)
{
var locationID = 0;
var domain = "domain";
var username = "xxx"; //username
var Password = "***"; //password
Debug.WriteLine("Location = "+location);
Debug.WriteLine("fileNames = " + fileNames);
using (new ImpersonateUser(username , domain, Password))
{
Debug.WriteLine("Files names = "+ fileNames);
foreach (string file in fileNames)
{
FileInfo files = new FileInfo(file);
files.Delete();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize("Files are successfully Deleted"));
}
}
Note
If I pass a string as a parameter without an array, it is working fine
Use the following
data: JSON.stringify({ location: location, fileNames: filesPaths }),
contentType: "application/json; charset=utf-8",
dataType: "json",
and change the input parameter datatype as List<string> instead of string[]
Just remove
dataType: "json",
from your ajax call.
and also check in your asmx file that it is decorated with
[System.Web.Script.Services.ScriptService]
try this.
I use asp.net and web forms.
In my project I have asmx web service
[WebMethod]
public string GetSomething()
{
// avoid circual reference(parent child)
List<RetUsers> res = repo.GetAllUser().Select(c => new RetUsers {User_ID = c.User_ID,User_Name = c.User_Name,Date_Expire = c.Date_Expire }).ToList();
string res1 = res.ToJson();
// extension methods
return res.ToJson();
}
And result is in this format.
[
{"User_ID":1,"User_Name":"Test 1","Date_Expire":null},
{"User_ID":2,"User_Name":"Test 2","Date_Expire":null}
]
How can I append to label this result in $.ajax sucess to get this output:
1 - Test 1, 2 - Test 2.
Return the list instead, and use [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute - it will create JSON object as return automatically:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<RetUsers> GetSomething()
{
// avoid circual reference(parent child)
List<RetUsers> res = repo.GetAllUser().Select(c => new RetUsers {User_ID = c.User_ID,User_Name = c.User_Name,Date_Expire = c.Date_Expire }).ToList();
return res;
}
And on JS side:
$.ajax(
{
type: "POST",
async: true,
url: YourMethodUrl,
data: {some data},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg)
{
var resultAsJson = msg.d // your return result is JS array
// Now you can loop over the array to get each object
for(var i in resultAsJson)
{
var user = resultAsJson[i]
var user_name = user.User_Name
// Here you append that value to your label
}
}
})
public ActionResult MyAjaxRequest(string args)
{
string error_message = string.Empty;
try
{
// successful
return Json(args);
}
catch (Exception e)
{
error_message = e.Message;
}
}
what maybe the an error here
I want to send JSON data to an action that will update some data. I then want to either redirect to another action or send back an error message to $.ajax.
Is possible with $.ajax otherwise how can I?
Becase following code does not redirect.
[code]
[HttpPost]
public ActionResult Save(RecipeViewModel postdata)
{
Recipe recipe = postdata.GetRecipe(_user.UserID);
int recipeid = _service.AddRecipe(recipe, null, true);
foreach (Ingredient ing in recipe.Ingredients)
{
ing.RecipeID = recipeid;
_service.AddIngredient(ing, null, false);
}
if (!postdata.Comment.IsEmpty())
{
Comment comment = new Comment();
comment.fldComment = postdata.Comment;
comment.RecipeID = recipeid;
comment.UserID = _user.UserID;
comment.EnteredByName = _user.Names;
comment.EnteredOn = DateTime.Now.ToString();
_service.AddComment(comment, null, false);
}
_service.SubmitChanges();
return RedirectToAction("View", "Recipe", new { id = recipeid });
}
u<script type="text/javascript">
$("#Save").click(function () {
var ingredients = $("#ingredients tr.ingredientdata").map(function (element, index) {
return {
ingredientName: $("td.ingredient", this).text(),
units: $("td.units", this).text(),
measure: $("td.measure", this).text()
};
}).toArray();
var json = {
RecipeTitle: $("#recipetitle").val(),
CategoryID: $("#category").val(),
PrepTime: $("#prepTime").val(),
PrepTimePeriod: $("#lstPrepTime").val(),
CookTime: $("#cookTime").val(),
CookTimePeriod: $("#lstCookTime").val(),
Rating: $("#rating").val(),
Method: $("#method").val(),
Comment: $("#comment").val(),
AccessLevel: $("#accessLevel").val(),
Ingredients: ingredients
};
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
Malcolm
You need to send back the Url and redirect it from the client script.
success: function (urlData) {
window.location.href = urlData ;
return false;
}
or you may show an error message based on the response received.
function EmpCode(empCode) {
var queryString = "";
var hasQuerystring = document.URL.indexOf('?');
if (hasQuerystring != -1) {
queryString = document.URL.substring(hasQuerystring + 1, document.URL.length);
if (queryString == 'id=1') {
$.ajax({
type: "POST",
url: "EmployeeBasicInfo.aspx/CheckEmpCode",
data: "{'empCode':" + empCode + "}",// Sending empCode which is a string
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var errorMsg = (msg.d);
if (errorMsg != 'NA') {
alert(errorMsg);
}
}
});
}
}
}
Here is my WebMethod
[WebMethod]
public static string CheckEmpCode(string empCode)
{
string empCod = "";
EmployeeFactory empFactory = new EmployeeFactory();
empCod = empFactory.CheckCode(empCode);
return empCod;
}
When i send the empCode as '11479' 0r any integers from Ajax the web method is calling. when i send the empcode as "C1026" or any string with characters then the webmethod is not getting called..
Please suggest me how to pass empCode which is having string value.
Put quotes around the EmpCode.Currently you are sending:
data: {'empCode': C1026}
You need to send:
data: {'empCode': 'C1026'}