Request.Form POSTED variable empty - c#

I have verified by using the browser debugger / network monitor that I am sending in a variable in an AJAX call called "search" and in the monitor it shows in the header as "search=test". I am trying to access this variable in the code behind but can't seem to find it? Here is my code for front and back-end, am I missing something?
Code Behind :
public class AJAXSearchLog : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string searchTerm = Convert.ToString(HttpContext.Current.Request.Form["search"]);
if(!string.IsNullOrEmpty(searchTerm)){
AspDotNetStorefrontCore.DB.ExecuteSQL("insert into TribSearch(SearchTerm,CustomerID,LocaleSetting) values(" + DB.SQuote(CommonLogic.Ellipses(searchTerm, 97, true)) + "," + '0' + "," + DB.SQuote("en-us") + ")");
}
context.Response.Clear();
context.Response.Write(searchTerm);
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
Front-End
window.onbeforeunload = function(e) {
if ($("#searchBox_text").val().length >= 2) {
var _search = $("#searchBox_text").val();
var url = "/AJAXSearchLog.ashx";
$.ajax({
async: false,
type: 'POST',
url: url,
data: {'search': _search},
contentType: 'application/json;',
dataType: 'json',
success: function(result) {
alert(result);
},
error: function(xhr, textStatus, errorThrown) {
console.log('error');
}
});
}
};

I have found that the data wasn't getting passed through when the contentType was set to 'application/json'. Also, to read the POST variable, Request.Params[] was needed. Here are the 2 lines of code that I changed :
in the front-end -
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
in the back-end -
string searchTerm = Convert.ToString(context.Request.Params["search"]);

Related

Delete image from folder using AJAX C#

I am trying to delete an image from a folder by using AJAX and C#. I have created a handler called Delete.ashx to delete the image. I also have an AJAX function to get the image path and pass the path to the handler
In AJAX I have a variable that gets the path which is stored in a textbox (just for now). I make an attempt to pass that path to my handler, however the problem is that the variable in the handler which I am trying to pass the data path to is always empty.
Here is my code:
Handler
public void ProcessRequest(HttpContext context)
{
string sFileName = context.Request["sFileName"]; //this variable is always empty
if (File.Exists(context.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context.Server.MapPath("~/images/" + sFileName));
context.Response.ContentType = "text/plain";
context.Response.Write("Image deleted Successfully!");
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Image Failed to Delete!");
}
}
AJAX
$(document).ready(function () {
$("#btnDelete").click(function () {
removeFile();
return false;
});
function removeFile() {
var FileName = $("#txtPath").val();
$.ajax({
url: 'Delete.ashx',
type: 'POST',
data: { 'sFileName': FileName},
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}
});
Please advise how I can pass data from AJAX to the handler so that the variable is not empty. Thank you.
try to get context from current HttpContext:
1
public void ProcessRequest(HttpContext context)
{
var context_= System.Web.HttpContext.Current;
string sFileName = context_.Request["sFileName"];
if (File.Exists(context_.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context_.Server.MapPath("~/images/" + sFileName));
context_.Response.ContentType = "text/plain";
context_.Response.Write("Image deleted Successfully!");
}
else
{
context_.Response.ContentType = "text/plain";
context_.Response.Write("Image Failed to Delete!");
}
}
2
Or send data with querystring from ajax
modify ajax:
url: 'Delete.ashx?sFileName=blabla',
server side:
var sFileName= Request.Form["sFileName"];
With the help of Mennan I have done the following and is working:
public void ProcessRequest(HttpContext context)
{
string sFileName = context.Request["sFileName"];
if (File.Exists(context.Server.MapPath("~/images/" + sFileName)))
{
File.Delete(context.Server.MapPath("~/images/" + sFileName));
context.Response.ContentType = "text/plain";
context.Response.Write("Image deleted Successfully!");
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Image Failed to Delete!");
}
}
function removeFile() {
var FileName = $("#txtPath").val();
$.ajax({
url: 'Delete.ashx?sFileName=' + FileName,
type: 'POST',
data: { 'sFileName': FileName},
contentType: false,
processData: false,
success: function (result) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
}

Issue with TypeScript and controller

So I'm converting a site form VB to C# and using TypeScript in the process. I have it successfully passing the data to the controller, however the controller post back to the same page instead to the next page.
Here's the TypeScript (full module here)
function formSubmission(submitId, submitUrl, formData, validation) {
if (!submitId || hasSubmit)
return false;
if (validation) {
if (!$("#empApp form").validate().form())
return false;
hasSubmit = true;
}
hasSubmit = true;
// add load status functionality
$(".modal").modal("show");
$.ajax({
type: "POST",
url: submitUrl,
data: formData,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
window.location.href = "/employment/application/references";
},
error: function (xhr, ajaxOptions, error) {
$(".modal-body").html("<h3>" + status + "<small>" + error + "</small></h3>");
setTimeout(function () {
$(".modal").modal("hide");
}, 100);
window.location.href = "/employment/application/work-experience";
}
});
}
Here's the Controller (full here)
[HttpPost, Route("Work-Experience")]
public ActionResult WorkExperience(List<EmploymentApplicationWorkExperience> appExperience)
{
EmploymentApplication empAppSession = getApplication();
if (!HasSession()) { return InvalidAppSession(); };
SetupViewBag();
if (!empAppSession.Steps.HasFlag(EmploymentApplication.ApplicationStepTypes.EducationSkills))
{
return PartialView(GetApplicationStepError());
}
if (ModelState.IsValid)
{
if (appExperience != null)
{
empAppSession.ApplicationWorkEperiences = appExperience;
// empAppSession.Application.empApWorkExperiences = (ICollection<empApWorkExperience>)appExperience;
empAppSession.StepCompleted(EmploymentApplication.ApplicationStepTypes.Workexperiences);
updateApplicationStep(empAppSession.Steps);
updateApplicationWorkExpriences(empAppSession.ApplicationWorkEperiences);
updateApplication(empAppSession.Application);
return RedirectToAction("References");
}
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
else
{
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
}
Used a unnecessary filter on Controller that if not valid, would continue to return the current page. Once removed, page continued with out post back issue.

Posting JSON object to asp.net server

i am trying to post some json data to to my asp.netserver on my localhost. The page to receive the code should be the master page, however i tried that and got "Error 403: Forbidden" so i tried my hands on a web service instead and now i am having a whole load of other issues. My main issue is that i could do this rather simply in PHP but i have no idea how to go about this in ASP.NET.
This is my js file:
// Get User Login Credentials
function authenticate() {
$(document).ready(function () {
var user = $('.login-box form #txtLoginUsername').val().trim();
var pass = $('.login-box form #txtLoginPass').val().trim();
// alert(user + " : " + pass);
$.ajax({
type: "POST",
url: "postback.asmx/Verify",
data: {
user: user,
pass: pass
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
if (response)
{
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () {});
}
}
});
});
}
Now i call this function on a button click event, i do not add my server code because it comprises of several lines of code i picked up from the net and tried to mash up to get my page to work, which it didn't. I would like to know a simple appropriate method of getting JSON objects from a post and return a value/array from my server.
Please i do not wish to use any asp.net server controls for certain reasons i am unable to disclose, but i have been restricted from using such controls.
You can´t put your WebMethod in an masterPage. Ajax is client side and you are getting the same error if you tried to acess site.master in your browser.
"Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.master' may be incorrect. Please review the URL below and make sure that it is spelled correctly. "
You can implement your WebMethod in other file .aspx and call by ajax.
I wrote an little example.
cs
[WebMethod(enableSession: true)]
public static void Verify(string user, String pass)
{
throw new Exception("I´m here");
}
js
function authenticate() {
$(document).ready(function () {
var user = $('#txtLoginUsername').val().trim();
var pass = $('#txtLoginPass').val().trim();
// alert(user + " : " + pass);
var data = {};
data.user = user;
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: JSON.stringify({
user: user,
pass: pass
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
if (response) {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
});
}
pay attention how Json is passing to data
data: JSON.stringify({
user: user,
pass: pass
}),
To call webservice, try pass json this way.
When you call web service there are same error message in browser´s console?
I think this is will help you.
You can use JSON.stringify() method as explained in follow
var jsonData=your Jason data;
Data:JSON.stringify(jsonData)
courtsey:
http://www.dotnetlines.com/forum/tabid/86/forumid/6/postid/72/scope/posts/Default.aspx#72
You can do like this.
[WebMethod]
public string Verify(string user,string pass)
{
//DataTable dt = YourMethod_ReturningDataTable();
//retrun dt.toJson();
//But in your case
bool IsAllowedtoLogin = true;
return IsAllowedtoLogin.toJson();
}
For this (toJson) method you have create a static class.This will convert even datatable to json format.
public static string toJson(this DataTable dataTable)
{
string[] StrDc = new string[dataTable.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
StrDc[i] = dataTable.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dataTable.TableName + "\" : [");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
TempStr = TempStr.Replace(dataTable.Columns[j] + j.ToString() + "¾", dataTable.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Note that data parameters are case sensitive. i.e user , pass .
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: "{'user':'"+yourvariable+"','pass':'"+yourvariable+"'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON && JSON.parse(data.d) || $.parseJSON(data.d);
if (data == "true") {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});

jquery ajax not returning data on success c# asp.net

I cant for the life of me figure out why my data being returned is empty. In fiddler i see the json
d=[{"response":[{"h":"h1"},{"h":"h1"}] }]
in fiddler there is a 200 status on the row where i see the json, but no other rows after that one ( maybe its not returning? ). This is the code i am using
$('.SomeLink').click(function () {
var sfn = $('#ID1').val();
var sfp = $('#ID2').val();
var sfi = $('#ID3').val();
var gid = $('#ID4').val();
$.ajax({
type: "POST",
cache: false,
url: '/AjaxHandler.aspx/GetNewHtml',
contentType: "application/json; charset=utf-8",
data: "{'a':'" + sfn + "','b':'" + sfp + "','c':'" + gid + "','d':'" + sfi + "'}",
dataType: "json",
success: function (data) {
alert(data.response[0].h); //acts like a syntax error/no alert box
alert(data); // [object Object]
alert(data.response); // undefined
alert(data.response.count); //acts like a syntax error/no alert box
},
error: function (e) {
alert("Error: " + e.responseText);
}
});
});
AjaxHandler.aspx
[System.Web.Services.WebMethod()]
public static string GetNewHtml(string a, string b, string c, string d)
{
List<Samp> samp = new List<Samp>()
{
new Samp{h = "h1"},
new Samp{h = "h1"}
};
return Serialize(new { response = samp });
}
private static string Serialize(object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
Samp Class
public class Samp
{
public string h = "";
}
This is my first time using jquery ajax with asp.net so im sure im missing something that is probably relatively simple. Im using .Net 4.0 , jquery 1.7.1 , iis 7.5
Try data.d for your return object:
alert(data.d);
its tripping over the quotes around the property names. try string indexes.
try
data["response"][0]["h"]
returns h1

Pass paramater to webservice on ajax

I have a simple web service with one argument :
public static string LoadComboNews(string id)
{
string strJSON = "";
DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
if (people != null && people.Count > 0)
{
//temp = new MyTable[people.Count];
string[][] jagArray = new string[people.Count][];
for (int i = 0; i < people.Count; i++)
{
jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(jagArray);
}
return strJSON;
}
on javascript I am trying to call it with parameter :
jQuery.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: "{'id':usrid}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
combonews = eval(msg.d);
}
});
UPDATE:
usrid is dynamic
Am I doing something wrong here?
data you are sending is invalid "{'id':usrid}"
this not a valid json
probably what you wanna do is assuming usrid is a variable
"{\"id\":"+usrid+"}"
with it shoudnt you be executing this command
Select * from News where person = '"+ id +"' Order by NewsId desc
Considering id is a string
also try this
combonews = JSON.stringify(msg);
Add WebMethod to the method
[WebMethod]
public static string LoadComboNews(string id)
And try this format
$.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: '{"id":"usrid"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
Or
data: '{"id":"' + usrid + '"}',

Categories

Resources