Service method name is not valid. from Hosted server - c#

I got this error
System.InvalidOperationException: ManageUser Web Service method name
is not valid. at
System.Web.Services.Protocols.HttpServerProtocol.Initialize() at
System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type,
HttpContext context, HttpRequest request, HttpResponse response,
Boolean& abortProcessing)
when I trying to call a webservice method from button click event using ajaxcall
$.ajax() {
type: "POST",
url: "RechargeService.asmx/ManageUser",
//data: "{objUser: " + JSON.stringify(objUsers) + "}",
data: "{Name:'" + Name + "',Address:'" + Address + "',City:'" + City + "',State:'" + State + "',Pincode:'" + Pincode + "',MobileNo:'" + MobileNo + "',Email:'" + Email + "',Password:'" + Password + "',Parameter:'" + Parameter + "',UserRole:'" + UserRole + "',UserStatus:'" + UserStatus + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (data) {
data = JSON.parse(data.d);
if (data.Sucess) {
$("#lblMsg").html('Registration done successfully');
$("#txtEmail").val('');
$("#txtPassword").val('');
$("#txtMobileNo").val('');
$("#txtConfirmPassword").val('');
$('#myModal1').hide();
alert("Your registration completed successfully");
} else {
alert("Already registered with this email id");
$("#txtEmail").val("");
}
},
error: function (xhr, status, error) {
alert(xhr.responseText + " \n " + status + " \n " + error);
alert("There was an error while processing. Please try again after some time.");
}
}
Method
[WebMethod]
Public string ManageUser()
{
}
This code works fine in local after hosting only i get the above error pls help me with this.. Thanks in advance

This can be caused by having null valued parameters in your WebMethod.
For example this:
public string GetDocument(int templateId, int? loginId = null)
...should be changed to this:
public string GetDocument(int templateId, int loginId)

There is a missing brackets () in the ajax function that should be Like this
$.ajax({
//Your Code...
});
Try this...

Possible REASON 1:
did u add this in above the service class
[System.Web.Script.Services.ScriptService]
Possible Reason 2:
Data should have sigle quotes for patameter names as well
data:{'Name':'" + Name + "','Address':'" + Address + "'}

Related

asp.net webapi works in browser and postman, but Jquery Ajax can't parse the returned JSON object

Fiddled with every imaginable combination of webapi controller and jquery ajax script which, when debugging, does make a get call to the controller, but it won't parse the data (in debug, the data is there!). PostMan and typing URL into browser works perfectly, so I believe there is (yet another) trick to get jquery.ajax to work.
the WebAPI controller method (which works):
namespace SearchWebsite.Controllers
{
public class MoreInfoController : ApiController
{
private string DBConnStr;
public MoreInfoController()
{
DBConnStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
LiveItem_Data.DBConnStr = DBConnStr;
}
[Route("api/getmoreinfo/{lid}")]
[HttpGet]
public async Task<IHttpActionResult> GetMoreInfo(string lid)
{
var retval = new AppCore.MoreInfo();
if (lid.Length == 36)
{
if (IsGUID(lid))
{
retval = await LiveItem_Data.GetMoreInfoAsync(lid);
}
}
return Ok(retval);
}
}
}
And I get the expected results when I call it via postman or the browser, like so:
https://localhost:44371/api/getmoreinfo/2A116FF3-E6C8-4EE3-88E5-99001DCCE36A
The jquery ajax method:
$(".popInfo").bind("click", function (e) {
var ListID = $(this).parent().parent().find('[id*=hidlid]').val();
$.ajax({
type: "get",
url: "../../api/GetMoreInfo/" + ListID,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
try {
var mi = jQuery.parseJSON(data);
var img = "";
if (mi.IMGLNK != "") { img = "<img src='" + mi.IMGLNK + "' class='img-responsive' />"; }
var title = "<a href='redir?lid=" + ListID + "' target='_blank' >" + mi.NAME + "</a>";
var btnV = "<a href='redir?lid=" + ListID + "' target='_blank' class='btn btn-success' ><span class='glyphicon glyphicon-shopping-cart'></span> Visit Website</a>";
var btnR = '</span> Report Problem';
var details = "<p><p>SKU: " + mi.SKU + "</p><p>MPN: " + mi.MPN + "</p><p>UPC: " + mi.UPC + "</p><p>Ship Weight: " + mi.WT + " lbs</p><p>Last Updated: " + formatJSONDate(mi.MD) + "</p></p>"
$('#moreinfo').find('.modal-title').html(title);
$('#moreinfo').find('.modal-body').html(img + '<p class="descr">' + mi.DESC + '</p>' + details);
$('#moreinfo').find('#btnVisit').html(btnV);
$('#moreinfo').find('#btnReport').html(btnR);
$('#moreinfo').off().modal('show');
} catch (e) {
alert("ERROR:" + e + " data: " + data + " mi: " + mi);
}
},
error: function (err) {
alert("error: " + err);
}
});
});
the try catch and alerts are for troubleshooting, however even though the data is in the data variable while stepping through and debugging, the "data" becomes undefined immediately after using parseJSON(), and, naturally, the variable "mi" is undefined as well and the error I trapped is "SyntaxError: Unexpected token u in JSON at position 0 data: [object Object]".
I'm at a loss as how to remedy this issue. (note: I am in the process of converting old ASMX services into MVC5 WebAPI 2.1 services, so DotNetCore answers won't work as it's a completely different beast, as is MVC4 and below)

Ajax and ASP.NET full string not being sent properly

I have an ajax call like so:
$.ajax({
type: "GET",
url: "/api/connection/NotifiyNextDepartment?questionId="
+ highestValue + "&department=" + jobTitle + "&customerId=" + customerID + "&jobNumber="
+ $("#communtiyDropdown").val() + $("#lotDropdown").val(),
dataType: "json",
cache: false,
success: function (data) {}
});
alert('Success, you\'re data has been saved!');
holder = [];
},
failure: function (errMsg) {
alert('Failed, somthing went wrong, please try again!');
}
jobTitle is equal to "Human Resources & Customer Experience Manager"
when I send it to .NET I only get this back:
public bool NotifiyNextDepartment(int questionid, string department, int customerId, string jobNumber)
{
}
Here department is equal to "Human Resources "
Why is .NET removing everything after the & and how do I fix this?
I think you should call encodeURIComponent on your parameters.
url: "/api/connection/NotifiyNextDepartment?questionId="
+ encodeURIComponent(highestValue) + "&department=" + encodeURIComponent(jobTitle) + "&customerId=" + encodeURIComponent(customerID) + "&jobNumber="
+ encodeURIComponent($("#communtiyDropdown").val() + $("#lotDropdown").val()),

JSon data Error

Hi i have one Json call by Ajax the code is
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Voyage.aspx/VoyageVessel_Set",
data: "{Action:'" + "Set" + "',VesselID:'" + "1" + "',VoyageMasterID:'" + "1" + "',StartTerminalID:'" + "1" + "',LastTerminalID:" + "" + ",EffectiveStartDate:'" + "09/09/09" + "',EffectiveEndDate:'" + "09/09/09" + "',PreviousVoyageID:'" + "1" + "',NextVoyageID:'" + "1" + "',DefaultVoyage:'" + "0" + "',Status:'" + "true" + "'}",
async: true,
dataType: "json",
success: function (data) {
try {
alert("Success for ADD button");
// $('#dvVesselTaggerInfo').html(html);
} catch (ex) {
alert(ex);
}
},
error: function (msg) {
alert(error);
}
});
Because of the Data which im trying to give my method is not calling, i hope i have written it in correct format but still i could not understand whats the probelm, can any one please help me.
in your code
data: "{Action:'" + "Set" + "',VesselID:'" + "1" + "',VoyageMasterID:'" + "1" + "',StartTerminalID:'" + "1" + "',LastTerminalID:" + "" + ",EffectiveStartDate:'" + "09/09/09" + "',EffectiveEndDate:'" + "09/09/09" + "',PreviousVoyageID:'" + "1" + "',NextVoyageID:'" + "1" + "',DefaultVoyage:'" + "0" + "',Status:'" + "true" + "'}",
Generally, each key and value in json data should have quotation marks, e.g:
{"Action" : "add", "VesselID", "1"}
Hope to help you :)

Json result Not Binding to aspx?

I have a service and it is returning json in the following format
Data {
"TerminalID": 21,
"TerminalName": "NewTested",
"PortID": 27,
"PortName": "Badu Island",
"EffectiveStart": "2013-03-20T00:00:00",
"EffectiveEnd": "2013-03-23T00:00:00",
"ServiceID": 2
}
and in my aspx page my code is:
<script type="text/javascript">
$(document).ready(function () {
$("#divImageGo").click(function () {
var valId = 2;
$.ajax({
type: "GET",
url: "VoyageOneService.svc/BindVoyageDetails" + valId,
//data: '{"ServiceID":"2"}',
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
ServiceSucceeded(result);
},
error: function (msg) {
$("#errorDiv").text(msg);
}
});
});
});
And success does the following:
function ServiceSucceeded(data) {
alert("Success");
for (var i = 0; i < data.d.length; i++) {
$("#dlistVoyageDetails").append("<tr><td>" + data.d[i].TerminalName + "</td><td>" + data.d[i].PortName + "</td><td>" + data.d[i].EffectiveStart + "</td></tr>" + data.d[i].EffectiveEnd + "</td></tr>");
}
}
function ServiceFailed(xhr) {
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
In this ..,
Iam getting My service called
Iam getting my Return value of json
Iam getting the Success fired with its alert msg
But I am unable to get the result. When I checked my alert with the result I am getting NULL
Remove the if condition and it will work.
As data.length is null hence you condition is not satisfied.
function ServiceSucceeded(data) {
alert("Success");
$("#dlistVoyageDetails").append("<tr><td>" + data.d[i].TerminalName + "</td><td>" + data.d[i].PortName + "</td><td>" + data.d[i].EffectiveStart + "</td></tr>" + data.d[i].EffectiveEnd + "</td></tr>");
}

How to save Data In Database to the controller

How to save Data In Database to the controller.i am using jquery to get data from the textbox. please help me.
Contactcontroller.cs
public ActionResult Create(string Name, string Company, string
Regarding, string Email, string Phone, string Message) {
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
try
{
// code
}
catch
{
}
jquery.js
$("#btnSubmit").click(function (event) {
var data = { Name: $("#txtbxName").val(), Company: $("#txtbxCompany").val(), Regarding:
$("#ddlRegarding").val(), Email: $("#txtbxEmail").val(), Phone: $("#txtbxPhone").val(), Message:
$("#txtarMessage").val()
}
$.ajax({
type: "POST",
url: "/Contact/Create", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "html",
success: function (result) {
$("#txtarMessage").val("");
alert(result);
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
alert('Thanks for sending info');
location.reload();
return false;
}
});
});
i am getting data to the textbox using jquery.
now i want to save the whole data in the database through Controller.
Jquery
$.post('/Controller/Create', { Name: $('#Name').val(), Company: "Company", Regarding: "", Email: "",Phone: "",Message: ""}, function (data) {
});
Controller Action
public JsonResult Create(string Name, string Company, string Regarding, string Email, string Phone, string Message)
{
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
return Json(body, JsonRequestBehavior.AllowGet);
}

Categories

Resources