JSon data Error - c#

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 :)

Related

How can I use autocomplete in a jQuery in an each loop?

I'm generating a table usinf jQuery. in each row I have an input field, that should search some values from DB usibg autocomplete. first row works perfectley but with the second I have problems, it returns in autocomplete only a value from the field above, I have no idea how can i fix it... can somebody help?
here is my code:
$.ajax({
type: "GET",
url: "/Home/JsonWeekEvents",
dataType: "JSON",
success: function (result) {
$.each(result, function (i, val) {
var trow = $('<tr/>').data("id", val.Id);
//trow.append('<td>' + val.Id + " " + '</td>');
trow.append('<td style="padding:5px; width:100px; height:70px"></td>');
trow.append('<td valign="top" style="padding:2px; width:150px; height:100px">' +
'<div class="ui-widget">' +
'<input size="10" maxlength="10" id="tagsM" class="tags" />' +
'<input type="button" id="addBtn" onclick="addEvent();" size="5" value="+" /><br/>' +
'<div style="text-align:center" id="desc_Num">' + val.Monday + '</div >' +
'</div >' +
'</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#weekEvents").html(tab);
},
error: function () {
alert("Failed! Please try again.");
}
});
var tab = $('<table class=MyTable border=1 ></table>');
var thead = $('<thead></thead>');
thead.append('<th style="padding:5px">FSE' + " " + '</th>');
thead.append('<th style="padding:5px">Monday' + " " + '</th>');
thead.append('<th style="padding:5px">Tuesday' + " " + '</th>');
thead.append('<th style="padding:5px">Wednesday' + " " + '</th>');
thead.append('<th style="padding:5px">Thursday' + " " + '</th>');
thead.append('<th style="padding:5px">Friday' + " " + '</th>');
thead.append('<th style="padding:5px">Saturday' + " " + '</th>');
thead.append('<th style="padding:5px">Sunday' + " " + '</th>');
tab.append(thead);
tab.on("focus", "input[class='tags']", function (e) {
//var prefix = $('.tags').val();
$('.tags').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/GetSearchValue",
dataType: "json",
data: { search: $('.tags').val() },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Title + ', ' + item.Description, value: item.Title,
Id: item.Id,
Title: item.Title,
Description: item.Description,
Location: item.Location
}
}));
},
error: function (xhr, status, error) {
alert("Error!" + xhr);
},
});
}
});
Would advise something like the following:
tab.on("focus", "input[class='tags']", function(e) {
if (!$(this).hasClass("ui-autocomplete")) {
$(this).autocomplete({
source: function(request, response) {
$.getJSON("/Home/GetSearchValue", {
search: request.term
},
function(data) {
response($.map(data, function(item) {
return {
label: item.Title + ', ' + item.Description,
value: item.Title,
Id: item.Id,
Title: item.Title,
Description: item.Description,
Location: item.Location
}
}));
});
}
});
}
});
This will initialize autocomplete on focus event. If it's already initialized, that will not be repeated. The source will perform a GET request and search for the request.term from the User's input on that specific field.

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()),

Service method name is not valid. from Hosted server

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 + "'}

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