Json parameter js + c# (MVC 3) - c#

I have a function in javascript and I send a json to c# by Ajax, but when I receive in c#, it's not a json. How I do it? If i put Response.Write(arr) in c#, the response is System.string[]. My project is in MVC 3
Function c#
public int salvar(string[] arr)
{
SqlConnection conexao = new SqlConnection(WebConfigurationManager.ConnectionStrings["strConexao"].ToString());
conexao.Open();
SqlTransaction trx = conexao.BeginTransaction();
try
{
//Truncate cliente_recurso
//BUProjetosDAL dal = new BUProjetosDAL();
// dal.excluirClientesRecurso(conexao, trx);
dtsRecursoClienteTableAdapters.RECURSO_CLIENTETabelaTableAdapter tabela = new dtsRecursoClienteTableAdapters.RECURSO_CLIENTETabelaTableAdapter();
for (int j = 0; j <= 149; j++) { // <- here
tabela.Insert(arr);
}
trx.Commit();
return 1;
}
catch (SqlException ex)
{
try
{
trx.Rollback();
return 0;
}
catch (Exception exRollback)
{
return 0;
}
}
}
Function js + ajax
$("#btnSalvar").on("click", function () {
var confirma = confirm("Deseja salvar os dados?");
if (confirma) {
var lista = jQuery("#tabelaRecurso").getDataIDs();
var total = lista.length;
var arr = [];
for (var i = 1; i <= lista.length; i++) {
var rowData = $("#tabelaRecurso").jqGrid('getRowData', i);
if (rowData.CD_CLIENTE != 0) {
arr[i - 1] = {
col1: rowData.CD_RECURSO,
col2: rowData.NM_RECURSO,
col3: rowData.CD_CLIENTE,
col4: rowData.LISTA_EMAIL,
col5: rowData.LISTA_EMAIL_COPIA
}
}
}
$.ajax({
type: 'POST',
url: '/Paginas/salvar',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(arr),
dataType: 'json',
success: function (dados) {
if (dados == 0) {
alert("Nao foi possivel salvar os dados");
}
}
});
}
});

Try using
$.ajax({
type: 'POST',
url: '/Paginas/salvar',
contentType: "application/json; charset=utf-8",
data: arr,
dataType: 'json',
traditional: true, --> use the traditional object serialization for the array
success: function (dados) {
if (dados == 0) {
alert("Nao foi possivel salvar os dados");
}
}
});

Related

MVC post with data and return json data

I have a controle like this
public JsonResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
I need to get that by following json by ajax request
var sizes = [];
$.ajax({
type: 'POST',
async: false,
data: { 'Id': selectedId },
url: "/<Controler name>/GetSizes",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
return false;
},
success: function (result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}
});
But this give me an Server error. How can i fix this.
replace your
url: "/<Controler name>/GetSizes",
by
url: "#Url.Action("GetSizes", "Controller_Name"),
and is you Ajax will have to be
async: false?
then try to use this as your Action
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
Also, try to put a break point on your action and see in debug mode if your Ajax reaches your Action.
this my demo, you can do the same:
$.ajax({
url: '#Url.Action("CheckCity", "BookingStarts")',
data: { packageId: packageid, cityId: valuecities[valuecities.length - 1] },
type: 'POST',
dataType: 'json',
success:
function(result) {
if (result.Status == true) {
$('#CheckoutDateHotel_#item.CityId').val(result.Date);
}
}
});
in controller :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CheckCity(int packageId, int cityId)
{
var packageCityModel = PackageDetails.GetPackageCitiesByPackageId(packageId).OfType<HMSService.PackageCity>();
var package = new PackageReservationMasterDal();
var itemPackage = package.GetPackageDetailByPackageId(packageId);
var result = "";
var city = packageCityModel.FirstOrDefault(x => x.CityId == cityId);
if (city != null)
{
result = itemPackage.TravelDateFrom.AddDays(city.NoOfNights).ToShortDateString();
}
return Json(new { Status = true, Date = result });
}
See the problem here is that you have not stringified your Data Transfer Object(DTO).
A cleaner approach will be this.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.0/json3.js"></script>
<script type="text/javascript">
var sizes = [];
var DTO = { 'Id': selectedId };
$.ajax({
type: 'POST',
async: false,
data: JSON.stringify(DTO),
url: "#Url.Action("GetSizes", "Home")",
dataType: 'json',
contentType: 'application/json'
}).done(function(result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}).fail(function(xhr) {
alert('Error: ' + xhr.statusText);
return false;
});
</script>
Please note the use of
JSON.stringify
#Url.Action helper
jqXHR.done(function( data, textStatus, jqXHR ) {});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
Also you are using async=false which I guess is to grab all the sizes before exiting from the function. jQuery.deferred will be an interesting read.

Internal server error in ajax post request

Guys I have problem with my ajax post request and it is not working for some dates i.e it does not hits controller but for some dates it works fine please help me to find out the bug
Here is my code
$("#getInfo").click(function ()
{
var elementValue = document.getElementById("tournamentID").value;
var startDateValue = document.getElementById("filterDateStartnew").value;
if (elementValue == null || elementValue == "" || startDateValue == null || startDateValue == "")
{
alert("please enter TournamentID and timestamp to get Info");
return false;
}
$.ajax({
type: "POST",
cache: false,
url: '/reports/gettournamentinfo',
data: { tournamentID: elementValue,date: startDateValue },
success: function (data)
{
var select = document.getElementById("TournamentLevel");
var length = select.options.length;
//Delete All Options
$('#TournamentLevel')
.find('option')
.remove()
.end()
var opt = document.createElement("option");
opt.text = "Any";
opt.value = -1;
document.getElementById("TournamentLevel").options.add(opt);
var count = data[0];
for (var i = 1; i <= count; i++)
{
var opt = document.createElement("option");
opt.text = i;
opt.value = i;
document.getElementById("TournamentLevel").options.add(opt);
}
for (var index = 1; index < data.length; ++index)
{
var opt = document.createElement("option");
opt.text = data[index];
opt.value = data[index];
document.getElementById("RunID").options.add(opt);
}
$("#SubmitForm").removeAttr('disabled');
},
error: function(data)
{
alert("there was no info for that tournamentID and that date");
$.unblockUI();
$('#TournamentLevel')
.find('option')
.remove()
.end()
return false;
}
});
return false;
});
Check for the data formats. For example if the client using dd/mm/yyyy and the server is expecting mm/dd/yyyy, you will see a HTTP 500 error as the model binder will fail to do the binding
Change your ajax post method like below.
$.ajax({ url: "/reports/gettournamentinfo", contentType: "application/json; charset=utf-8", type: "POST",
data: '{"tournamentID":"' + elementValue+ '", "date":"' + startDateValue + '"}',
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});

Invalid web service call, missing value for parameter with asmx web service

I have this error : "Invalid web service call, missing value for parameter " when I call a web service method with a parameter.
I'm testing with a web service method without parameter that returns the same type of object and it works well.
Here is my web service method :
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public ResponseStatistic_3 Statistic_3(string klant)
{
Statistic_3[] items = Helper.Helper_Statistic_3(klant).ToArray();
ResponseStatistic_3 response = new ResponseStatistic_3(items);
return response;
}
Here is my javascript code, I retrieve the good value in kla variable :
function getStatistic3() {
var response;
var allstat3 = [];
var kla = $('#Select1').val();
var dataJSon = { klant: kla }
if (kla) {
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: dataJSon,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: false,
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
} else {
alert("statistic 3 null");
}
}
I'm testing too with JSON.stringify({ klant: kla }) and I have the same error.
I looked at several forums but in vain.
What's wrong?
Your webservice method requires a string parameter, but you send the JSON representation of a customer object. I think the build-in JavaScriptSerializer is trying to deserialize your parameter and is causing the error. I adjusted your code in the example below:
function getStatistic3() {
var response;
var allstat3 = [];
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: $('#Select1').val(),
dataType: 'json',
processData: false,
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
}
Webservice method
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public ResponseStatistic_3 Statistic_3(string klant)
{
Statistic_3[] items = Helper.Helper_Statistic_3(klant).ToArray();
ResponseStatistic_3 response = new ResponseStatistic_3(items);
return response;
}
You need to stringify the parameter sefore sending it to the web service using JSON.stringify() method.
function getStatistic3() {
var response;
var allstat3 = [];
var kla = $('#Select1').val();
**var dataJSon = JSON.stringify({ klant: kla })**
if (kla) {
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: dataJSon,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: false,
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
} else {
alert("statistic 3 null");
}
}

reading a string table jquery ajax success function

the code:
[WebMethod]
public static string [] GetMorechatMsgs(int toclient, int fromclient, int top)
{
string [] List =new string[2];
int chatcount = new ChatPage().GetAllMsgCount(toclient, fromclient);
if (top <= chatcount)
{
string toreturn=new ChatPage().GetChat(fromclient, toclient, "", top);
List[0]= toreturn;
List[1] = chatcount.ToString();
}
else {
List = null;
}
return List;
}
html:
$.ajax({
type: "POST",
url: "ChatPage.aspx/GetMorechatMsgs",
data: "{'toclient':'" + ToClient + "','fromclient': '" + fromClient + "','top': '" + $("#MsgCount").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != "") {
// how to read the returned table
}
else {
}
},
error: function (xhr) {
alert("responseText: " + xhr.responseText);
}
});
How can i read the returned string array on success ?
serialize the list of your string i.e
change your method to this:
[WebMethod]
public static string GetMorechatMsgs(int toclient, int fromclient, int top)
{
/// your usual code
return new JavaScriptSerializer().Serialze(list);
}
and read returned data like this:
success: function (data) {
var jsonData =$.parseJSON(data.d);
for(var i=0; i<jsonData.length; i++){
console.log(jsonData[i]);
}
}
The WebMethod will return your string array in the form ["string", "string", "string", ...], therefore, simply loop through the array in the way Manish demonstrated:
success: function (data) {
var jsonData =$.parseJSON(data.d);
for(var i=0; i<jsonData.length; i++){
var theString = jsonData[i];
//Do something with the string
}
}

Two Listboxes with same value, I need to remove identicial value from one Listbox

I have two ASP ListBoxes. As you can see below, lbAvailable is populated on PageLoad with WebMethod and populates all cities. LbChoosen is populated depending on DropDown Value Chosen. The Dropdown has 4 options(ALL, Top25, Top50, Top100). for example if you choose Top 25 which is value 4, lbChosen populates top 25 cities (This all works).
MY PROBLEM IS lbAvaliable always populates all cities. So if i chose top 25 which populates top25 cities into lbChoosen, how can those value (top25 cities) be removed from lbAvailable
function LoadMarketsAvailableJS() {
var ddlFootprint = $('#ddlFootprint');
var lbChoosen = $('#lbChoosen');
var lbAvailable = $('#lbAvailable');
lbChoosen.empty();
var SelectedMarkets = [];
var url = "";
//Load lbAvailable on Page Load with all Markets
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Campaign.aspx/LoadAvailableMarkets",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
$("#lbAvailable").append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function(result) {
alert("Error");
}
});
//Check DropdownList
if (parseInt(ddlFootprint.val()) == 1) {
url = 'Campaign.aspx/LoadAvailableMarkets';
} else if (parseInt(ddlFootprint.val()) == 2) {
url = 'Campaign.aspx/LoadTop100Markets';
}
else if (parseInt(ddlFootprint.val()) == 3) {
url = 'Campaign.aspx/LoadTop50Markets';
}
else if (parseInt(ddlFootprint.val()) == 4) {
url = 'Campaign.aspx/LoadTop25Markets';
}
else if (parseInt(ddlFootprint.val()) == 5) {
url = 'Campaign.aspx/LoadAvailableMarkets';
}
//Load Select Dropdown Value to lbChoosen
if (url.length > 0) {
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
}
}
Assuming I've understood what you're asking, if you want to remove options from lbAvailable as they're added to lbChoosen you should be add the following line:
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
So your code will look something like:
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
}
}
},

Categories