Unknown web method in asp.net - asp.net

In the below code I have a textbox .My aim is when I focus on textbox it will call the server side code through ajax.But I got a error unknown web method txtField_GotFocus parameter name method name.Please help me to rectify the error.
design code:
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
//alert("success message here if you want to debug");
},
error: function (xhr) {
var rawHTML = xhr.responseText;
var strBegin = "<" + "title>";
var strEnd = "</" + "title>";
var index1 = rawHTML.indexOf(strBegin);
var index2 = rawHTML.indexOf(strEnd);
if (index2 > index1) {
var msg = rawHTML.substr(index1 + strBegin.length, index2 - (index1 + strEnd.length - 1));
alert("error: " + msg);
} else {
alert("General error, check connection");
}
}
});
});
});
<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" OnTextChanged="txtField_TextChanged" ClientIDMode="Static"></asp:TextBox>
field.ascx:
public static void txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
}

You are missing [WebMethod] annotation. Also i have modified your code
[WebMethod]
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];//oops i got my super data
//code...
return "awesome, it works!";
}
Check this Article
Your refactored ajax code
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg);//awesome, it works!
},
error: function (xhr) {
}
});
});
});

Data returned form Server is stored in msg.d field. If you return a single value, you should get it using msg.d. If you return a JSON serialized object you have to parse it using JSON.parse(msg.d)
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg.d);//awesome, it works!
},
error: function (xhr) {
}
});
});
});

Related

formdata in ajax call

When I pass formdata in ajax call after json return it does not return on Success or error block just printing value on browser
// And my Controller side code is
[HttpPost]
public JsonResult Create(InquiryModel model)
{
var inquiry = _inquiryService.GetInquiryById(model.Id);
return Json(inquiry.Id, JsonRequestBehavior.AllowGet);
}
// View side
var formData = new FormData();
jQuery.each(jQuery('#QuotationDocument')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
contentType: false,
processData: false,
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});
when I pass only formData it works fine
Try like this;
$.ajax({
url: '#Url.Action("Create", "Inquiry")',
data: formData,
datatype: "json",
type: "POST",
success: function (data) {
alert("ssss");
},
error: function (msg) {
alert("error", msg.statusText + ". Press F12 for details");
}
});

Call a web method using jQuery Ajax

I want to create an Autocomplete field for a search option. I have tried with following code.
But the web method doesn't fire when the Autocomplete function is execution.
What will be the reason ?
Here is the jQuery function:
<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
source:function (request, response) {
$.ajax ({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "~/Services/AutoComplete.asmx/GetFarmersByName",
data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {
response($(data.d, function (item) {
return {
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
Here is the web method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
this._personalData = new personalData();
int cky = 45;
CdMa cdMas = new CdMa();
cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
int prefixKy = cdMas.CdKy;
List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();
list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
return list;
}
Make sure you hit the webservice function by having breakpoint on your service function. Please change your script to below:
<script type="text/javascript">
$(function () {
$("#<%=tags.ClientID %>").autocomplete
({
source:
function (request, response) {
$.ajax
({
url: " <%=ResolveUrl("~/Services/AutoComplete.asmx/GetFarmersByName") %>",
data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
response($(data.d, function (item)
{
return
{
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
Above your service class add [System.Web.Script.Services.ScriptService]
Or you can do this in an asp.net page!
add the static keyword and change the webservice to ASP.NET page!
public static string GetFarmersByName(string name)
For example:
A.aspx:
$.ajax({
type: "POST",
url: "A.aspx/GetSN",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async:false,
success: function (json) {
var msg = JSON.parse(json.d);
sn = msg;
},
failure: function () {
alert("Sorry,there is a error!");
}
});
Then in your A.aspx.cs type in:
[WebMethod]
public static string GetSN()
{
Random RN = new Random();
string year = DateTime.Now.ToString("yy").ToString();
string MonAndDate = DateTime.Now.ToString("MMdd").ToString();
string Hour = DateTime.Now.ToString("HHMMss").ToString() + DateTime.Now.Millisecond.ToString() + RN.Next(100, 900).ToString();
string SerialNumber = year + MonAndDate + Hour;
return JsonConvert.SerializeObject(SerialNumber);
}
Assuming tags as your textbox, set data as { 'name': '" + request.term + "'}
$("#<%=tags.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "Services/AutoComplete.asmx/GetFarmersByName",
data: "{ 'name': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
},
});
},
minLength: 0,
focus: function () {
// prevent value inserted on focus
return false;
},
});
debug on method GetFarmersByName,
NOTE: Check have you uncomment [System.Web.Script.Services.ScriptService] on .asmx page.
Post again!!!
Test.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(function(){
$("#Button1").bind("click",function(){
$.ajax({
type: "POST",
url: "Test.asmx/GetFarmersByName",
data:"{'aaa':'zhangsan'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function (json) {
},
failure: function () {
alert("Sorry,there is a error!");
}
});
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
</div>
</form>
</body>
</html>
Test.asmx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace TestWebForm
{
/// <summary>
/// Summary description for Test
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Test : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
List<string> list = new List<string>();
list.Add(aaa);
return list;
}
}
}
Paste this method inside code behind file where you are calling this method. Change url to url: "Test.aspx/GetFarmersByName" and then test it. Its much clean code rather then Web Service.
using System.Web.Script.Services;
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
List<string> list = new List<string>();
list.Add(aaa);
return list;
}
try this -
<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
source:function (request, response) {
var obj = JSON.Stringfy("{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}");
$.ajax ({
type: "POST",
url: "~/Services/AutoComplete.asmx/GetFarmersByName",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {
response($(data.d, function (item) {
return {
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
and the webmethod-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
this._personalData = new personalData();
int cky = 45;
CdMa cdMas = new CdMa();
cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
int prefixKy = cdMas.CdKy;
List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();
list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
return list;
}

Passing parameters in ajax call

I'm trying to make an ajax call to the controller method. without parameter it works fine. Once i add the parameter i always receive a null parameter to the cotroller. I think i have correctly done the parameter passing in ajax call.
<script type="text/javascript">
$(document).ready(function () {
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: '{"stockID":"' + dropDownID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data.Result);
}
function errorFunc() {
alert('error');
}
})
});
</script>
Controller:
[HttpGet]
public ActionResult GetStockPrice()
{
return View();
}
[HttpPost]
[ActionName("GetStockPrice")]
public ActionResult GetStockPrice1(string stockID)//I get the null parameter here
{
DeliveryRepository rep = new DeliveryRepository();
var value = rep.GetStockPrice(stockID);
return Json(new { Result = value }, JsonRequestBehavior.AllowGet);
}
It's because you are treating the data as a string
data: '{"stockID":"' + dropDownID + '"}',
you can change it to:
data: { stockID: dropDownID },
in some cases, depending on the parameter declared in your controller method, you need to serialize the data. If you need to do that then this is how you would do it:
var o = { argName: some_value };
$.ajax({
// some other config goes here
data: JSON.stringify(o),
});
try data: { stockID : dropDownID},
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
// $(this).val(); is better
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: { stockID : dropDownID},
....
Try specifying:
data: { stockID : dropDownID },
It looks like you're passing up "stockID" not stockID.
A good tool to use for this is Fiddler, it will allow you to see if the Controller action is hit and what data was sent upto the server.

Redirect from Webmethod in Asp.Net

Am new to Asp.Net Programming, Have just started a web project.
Am calling a WebMethod from Aspx page using JSON like below:
<script type="text/javascript">
function getLogin() {
var userName = document.getElementById('TextBox1').value;
$.ajax({
type: "POST",
url: "Services/LogService.asmx/authenticateLogin",
data: "{'userName':'" +userName.toString()+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d)
},
error: function (xhr, status, error) {
// alert(textStatus);
DisplayError(xhr);
}
});
}
function DisplayError(xhr) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message); }
</script>
And WebMethod :
[WebMethod]
public string authenticateLogin(string userName)
{
LoginBO loginBO = new LoginBO();
loginBO.userName = userName.ToString().Trim();
string result = "";
try
{
LoginDao loginDao = DAOFactory.GetDaoFactory().getLoginDao();
result = loginDao.selectUser(loginBO);
}
catch (DBConnectionException)
{
//result = "DB Conenction";
throw new Exception("DB Connection is Down");
}
catch (InvalidLoginException)
{
//HttpResponse res = new HttpResponse();
//HttpResponse.ReferenceEquals.Redirect("~/Login.aspx");
throw new InvalidLoginException("Login Is Invalid");
}
catch (Exception)
{
throw new Exception("Uanble to Fetch ");
}
int ctx = Context.Response.StatusCode;
return result;
}
After Successful Authentication, I want to redirect user to another aspx page.
What is the best practice to do ?
Thanks
Samuel
Add a redirect to the success section of your getLogin() function:
success:
function (response) {
alert(response.d);
windows.location.href = "http://url.for.redirect";
}
(Or use some other method for redirecting within jQuery/Javascript).
In your Ajax method
success: function(msg) {
alert(response.d);
window.location = "xyz.aspx";
},
success: function (response) {
alert(response.d)
window.location.href = "some.aspx";.
}
I think it will help you.

How to consume the return value of a webservice in jquery ajax call?

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

Resources