How to pass json string to webmethod c# ASP.NET - javascript

Im trying to stringify a javascript object and then pass the string as a parameter to a WebMethod in Code Behind. I can't get it to work as I get a Internal Server Error of 500 and the stacktrace says that value is missing for parameter.
Here is the javascript code:
var jSon = JSON.stringify(javascriptObject);
// "{"Foretagsnamn":"Avector","BGFarg":"000000","TextColor":"fafafa","FooterFarg":"ffffff","FooterColor":"000000","FooterLinkColor":"050505","FeaturedBorderColor":"","HoverFarg":"12ebeb","RutFarg":"0d0d0d","SelectedRutFarg":"","RutColor":"FFFFFF","LankColor":"","DelaMedSig":"1","PersonalSida":"0","StartpageTitle":"","StartpageDescription":"","GoogleMaps":"<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"https://maps.google.se/maps?f=q&source=embed&hl=sv&geocode=&q=Avector AB&aq=&sll=56.225986,12.870827&sspn=0.076248,0.154324&ie=UTF8&hq=Avector AB&hnear=&t=m&cid=645910733081021950&iwloc=A&ll=56.224594,12.859229&spn=0,0&output=embed\"></iframe><br /><small>Visa större karta</small>","HittaKartaUrl":"http://www.hitta.se/avector ab/ängelholm/hxTP-4v1HG?vad=Avector AB","EniroKartaUrl":"http://kartor.eniro.se/m/aKkhi","Ikoner":"2","Email":"info#avector.com","AdressSida":"1","shadowColor":"ffffff","lineColor":"2b292b","MenuHoverIcon":"Välj bild från server","fontFamily":"Verdana","supportText":"Support Avector","captcha":true,"metaKeywords":"","ShowSupportInFooter":true}"
$.ajax({
type: "POST",
url: "Post/Installningar.aspx/Updatera",
data: jSon,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var resultAsString = result.d;
//_this.parent().siblings('.SavedStatus').html(resultAsString);
if (resultAsString == "1") { // Gick bra att spara.
alert("Uppgifterna är sparade.");
document.location = document.location;
}
else {
$('#StatusText').html("Gick inte att spara uppgifterna.");
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
And here Is the webmethod:
[WebMethod]
public static string Updatera(string jSon)
{
It feels like I've tried everything that I've found when searching by google and here on SO.
I've also tried this guide that many refer to: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Any ideas?

First, you need to use:
var jSon = JSON.stringify({obj:javascriptObject});
instead of:
var jSon = JSON.stringify(javascriptObject);
Then your WebMethod would be like:
[WebMethod]
public static string Updatera(aData obj)
{
// logic code
}
Now here aData is your class something like below :
public class aData {
public string Foretagsnamn { get; set; }
public string BGFarg { get; set; }
public string TextColor { get; set; }
public string FooterFarg { get; set; }
public string Email { get; set; }
}
So your final code look like
jQuery:
var jSon = JSON.stringify({ obj:javascriptObject });
$.ajax({
type: "POST",
url: "Post/Installningar.aspx/Updatera",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response){
// Do something
}
function OnErrorCall(){
// Do something
}
Code Behind:
public class aData {
public string Foretagsnamn { get; set; }
public string BGFarg { get; set; }
public string TextColor { get; set; }
public string FooterFarg { get; set; }
public string Email { get; set; }
}
[WebMethod]
public static string Updatera(aData obj)
{
// Logic code
}

Use this format for ajax post format :
var jSon = JSON.stringify(javascriptObject);
Your Json Format will be like this :
'{name: "' + name +'" }',
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Installningar.aspx/Updatera",
data: jSon;
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
Follow this step for complete run your code :
http://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

Related

Javascript : Pass complex object to my controlleur (asp core)

Trying to send object to my controller :
$.ajax({
type: "POST",
url: '/Groups/Invite',
contentType: "application/json",
data: JSON.stringify(UserInvited),
dataType: "json",
success: function () {},
error: function (xhr, status, error) {}
});
In debug mode, my data is :
{"Id":"47","Guest":[{"Key":"","Pseudo":"Lolo01500","Del":false,"Add":true}]}
My Action in controller :
[HttpPost, ActionName("Invite")]
public IActionResult Invite(GroupInviteVM groupInviteVM)
{
// TODO
return Json(true);
}
And Targets object classes :
public class ItemInvite
{
public string Key { get; set; }
public string Pseudo { get; set; }
public bool Add { get; set; }
public bool Del { get; set; }
}
public class GroupInviteVM
{
public int Id { get; set; }
List<ItemInvite> Guest { get; set; }
public GroupInviteVM()
{
Guest = new List<ItemInvite>();
}
}
When execute, only the Id is updated ...
Somebody could help me ?
T.Y.
When execute, only the Id is updated ...
That is because the Guest property is not public.Add public modifier like below:
public class GroupInviteVM
{
public int Id { get; set; }
public List<ItemInvite> Guest { get; set; }//change this
public GroupInviteVM()
{
Guest = new List<ItemInvite>();
}
}
The whole demo:
View:
<script>
var UserInvited = {
Id: 1,
Guest: [{
Key: "aaa",
Pseudo: "asd"
}]
};
console.log(JSON.stringify(UserInvited));
$.ajax({
type: "POST",
url: '/Groups/Invite',
contentType: "application/json",
data: JSON.stringify(UserInvited),
dataType: "json",
success: function () { },
error: function (xhr, status, error) { }
});
</script>
Controller:
[HttpPost, ActionName("Invite")]
public IActionResult Invite([FromBody]GroupInviteVM groupInviteVM)
{
// TODO
return Json(true);
}

Get json data from ajax,process it,return answer

I have some troubles with transfer json data.
I have some dynamic page. I collect data to json object "Filters".
var Filters = { daterange: $('#daterange').val(), shop: val_shop, pr: val_pr, plan: val_plan, TabsList: TabsList }
$.ajax({
url: "/Reports/Report_2",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(
Filters
)
});
I try get it with JObject.
public IActionResult Report_2() //main Action
{
return View();
}
[HttpPost]
public async Task<IActionResult> Report_2([FromBody]JObject jsonResult)//catch json object
{
//do something
return View(_context.MyDatabase.Result);//return data from database for table(Razor Page)
}
I get Error 415. =(
If I try don't overload Report_2 Action().
$.ajax({
url: "/Reports/Report_2_Filter",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(
Filters
)
});
[HttpPost]
public async Task<JObject> Report_2_Filter([FromBody]JObject jsonResult)
{
return jsonResult;
}
I don't know how return result on Report_2 page. I need result on Report_2 Action becouse I must fill table on Report_2 page. I'm newbee in web, so I will be greateful for any help.
May be you need write ("");
var Filters = { "daterange": $('#daterange').val(), "shop": val_shop, "pr": val_pr, "plan": val_plan, "TabsList": TabsList }
You can add a function to be executed on success. Try to add the following to your ajax request:
success: function(data){
// Do something here
}
Have a look here to see the ajax events.
My solution:
I create class which stores variables:
public class FilterModel
{
public string var1{ get; set; }
public string var2{ get; set; }
public string var3{ get; set; }
public string var4{ get; set; }
public List<string> var5{ get; set; }
}
[HttpPost]
public IActionResult Report_2(FilterModel filter)
{
FilterLogic filterLogic = new FilterLogic(_context);
var result = filterLogic.GetResult(filter);
return View();
}
In JS I use jQuery function $.post
$.post("/Reports/Report_2", { var1: $('#var1').val(), var2: var2, var3: var3, var4: var4, var5: var5});

Sending data with post ajax to asp.net MVC controller

I am tried sent a data from view with ajax (POST) to controller in JSON format. From console.log, data is correct but data in controller missing...
Here is controller:
[HttpPost]
public ActionResult SavePermission(TestData testData)
{
return Json("DONE");
}
Here is model:
namespace INTRANETv4.Models
{
public class TestData
{
public string id { get; set; }
public bool read { get; set; }
public bool write { get; set; }
public bool delete { get; set; }
}
}
Here is javascript function from View:
function Save() {
var rows = document.getElementById("userTable").getElementsByTagName("tr");
var output = [];
for (i = 1; i < rows.length; i++) {
output.push({
id: rows[i].id,
read: rows[i].getElementsByTagName("td")[2].getElementsByTagName("input")[0].checked,
write: rows[i].getElementsByTagName("td")[3].getElementsByTagName("input")[0].checked,
delete: rows[i].getElementsByTagName("td")[4].getElementsByTagName("input")[0].checked
});
}
var myJSON = JSON.stringify(output);
console.log(myJSON);
$.ajax({
type: "POST",
contentType: "application/json",
data: myJSON,
url: "/Files/SavePermission",
dataType: "json"
});
}
Here is console.log of myJSON:
And here is content of testData from controller while debugging:
When i used string testData, because i worried about to convert, string was null. Thank you for any advice.
try
you model change to List<TestData> testData
and data change to JSON.stringify({ testData: output }),
$.ajax({
type: "POST",
contentType: "application/json",
data: JSON.stringify({ testData: output }),
url: "/Files/SavePermission",
dataType: "json"
});

Why is my posted data null in the Controller target of this AJAX call?

I have modeled (no pun intended) my AJAX call on the answer here from logan filley, which seems sensible and likely to work. This is the jquery I have in the View:
$("#btnSaveConfig").click(function () {
var saveConfigModel = {
unit: $('#unitsselect').val(),
scheduleProduceUsage: $('#ckbx_produceusage').checked,
scheduleDeliveryPerformance: $('#ckbx_deliveryperformance').checked,
scheduleFillRate: $('#ckbx_fillratebycustomer_location').checked,
schedulePriceCompliance: $('#ckbx_pricecompliance').checked,
// TODO: Finish this by storing add'l emails in an array along with the three on the page;
recipients: $('#email1').val(),
generationDayOfMonth: $('#dayofmonthselect').val(),
generationOrdinal: $('#ordinalselect').val(),
generationDayOfWeek: $('#dayofweekselect').val(),
generationWeekOrMonth: $('#weekormonthselect').val(),
daterangeFromProduceUsage: $('#produsagefrom').val(),
daterangeToProduceUsage: $('#produsageto').val(),
daterangeFromDeliveryPerformance: $('#delperffrom').val(),
daterangeToDeliveryPerformance: $('#delperfto').val(),
daterangeFromFillRate: $('#fillratefrom').val(),
daterangeToFillRate: $('#fillrateto').val(),
daterangeFromPriceCompliance: $('#pricecompliancefrom').val(),
daterangeToPriceCompliance: $('#pricecomplianceto').val()
}
$.ajax({
type:"POST",
url:'#Url.Action("PostUnitConfig", "SaveConfig")',
async:true,
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(saveConfigModel)
});
}); // $("#btnSaveConfig").click()
...and this is my Model:
public class SaveConfigModel
{
public UnitConfigVals unitConfigVals { get; set; }
public class UnitConfigVals
{
public string unit { get; set; }
public bool scheduleProduceUsage { get; set; }
public bool scheduleDeliveryPerformance { get; set; }
public bool scheduleFillRate { get; set; }
public bool schedulePriceCompliance { get; set; }
public List<string> recipients { get; set; }
public int generationDayOfMonth { get; set; }
public string generationOrdinal { get; set; }
public string generationDayOfWeek { get; set; }
public string generationWeekOrMonth { get; set; }
public int daterangeFromProduceUsage { get; set; }
public int daterangeToProduceUsage { get; set; }
public int daterangeFromDeliveryPerformance { get; set; }
public int daterangeToDeliveryPerformance { get; set; }
public int daterangeFromFillRate { get; set; }
public int daterangeToFillRate { get; set; }
public int daterangeFromPriceCompliance { get; set; }
public int daterangeToPriceCompliance { get; set; }
}
}
...and Controller (obviously ultra-spartan at the moment):
public class SaveConfigController : Controller
{
public ActionResult PostUnitConfig(SaveConfigModel model)
{
try
{
string s = model.unitConfigVals.unit;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Json(new { success = true });
}
}
I am reaching the breakpoint in my Controller (on the "string s = model.unitConfigVals.unit;" line), but it throws an exception because the value of "model" is null. Why? Have I got something in my AJAX call wrong, or...?!?
UPDATE
I changed my jquery to this (changed boolean assignments and appended a semicolon):
$("#btnSaveConfig").click(function() {
var saveConfigModel = {
unit: $('#unitsselect').val(),
scheduleProduceUsage: $('#ckbx_produceusage').attr('checked'),
scheduleDeliveryPerformance:
. . .
};
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
//contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ data: saveConfigModel })
});
});
...but the Controller is still passed a null model.
UPDATE 2
Now I changed "attr('checked')" to "is('checked')" but no difference...
UPDATE 3
"model" is null here in the Controller:
public class SaveConfigController : Controller
{
public ActionResult PostUnitConfig(SaveConfigModel model)
...when the AJAX call is like this:
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
dataType: "json",
data: saveConfigModel
});
...and also when the AJAX call is like this:
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
data: saveConfigModel
});
...and this:
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ model: saveConfigModel })
});
Do I need the "async: true"? I don't use that in my (working) GET AJAX calls. Similarly, do I need "cache: false"? I do use that in those working GET AJAX calls...
UPDATE 4
Even when I provide just some bogus vals:
var saveConfigModel = {
unit: 'Buford', //$('#unitsselect').val(),
scheduleProduceUsage: true, //$('#ckbx_produceusage').is(':checked'),
scheduleDeliveryPerformance: false, // $('#ckbx_deliveryperformance').is(':checked'),
scheduleFillRate: false, //$('#ckbx_fillratebycustomer_location').is('checked'),
schedulePriceCompliance: false, //$('#ckbx_pricecompliance').is('checked'),
// TODO: Finish this by storing add'l emails in an array along with the three on the page; might be as easy as declaring an array like this one, and adding to it as necessary
recipients: 'platypus#whatever.com', // $('#email1').val(),
generationDayOfMonth: '2nd', //$('#dayofmonthselect').val(),
generationOrdinal: 'First', //$('#ordinalselect').val(),
generationDayOfWeek: 'Thursday', // $('#dayofweekselect').val(),
generationWeekOrMonth: 'month', // $('#weekormonthselect').val(),
daterangeFromProduceUsage: $('#produsagefrom').val(),
daterangeToProduceUsage: $('#produsageto').val(),
daterangeFromDeliveryPerformance: '1', // $('#delperffrom').val(),
daterangeToDeliveryPerformance: '1', //$('#delperfto').val(),
daterangeFromFillRate: '1', //$('#fillratefrom').val(),
daterangeToFillRate: '1', //$('#fillrateto').val(),
daterangeFromPriceCompliance: '1', //$('#pricecompliancefrom').val(),
daterangeToPriceCompliance: '1' //$('#pricecomplianceto').val()
};
...it still winds up at the Controller null like forevermore before.
And then, grasping at straws, I even encased the boolean values in single quotes ('true' and 'false'), but that also (probably predictably) made no difference either.
UPDATE 5
For future generations, this is the AJAX that works:
$.ajax({
type: "POST",
url: '#Url.Action("PostUnitConfig", "SaveConfig")',
async: true,
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ model: saveConfigModel })
});
Since the values you posting back are for your nested UnitConfigVals class (not SaveConfigModel, then you controller method should be
public ActionResult PostUnitConfig(SaveConfigModel.UnitConfigVals model)
and the ajax data option needs to be
data: JSON.stringify({ model: saveConfigModel })
Alternatively you could keep the current controller method and use
data: JSON.stringify({ model: { unitConfigVals: saveConfigModel }})
although it seems a little odd that you using a nested class here.
A few other issues with your initial code
$('#ckbx_produceusage').checked will return undefined, and it
needs to be $('#ckbx_produceusage').is(':checked') which will
return true or false
Since recipients is List<string>, it will need to be
recipients: [ 'someValue', 'anotherValue', etc ]
However all this code to build you json data not really necessary, and if your view is generated correctly using the strongly typed HtmlHelper methods, then your ajax call can be as simple as
$.ajax({
type:"POST",
url:'#Url.Action("PostUnitConfig", "SaveConfig")',
dataType: "json",
data: $('form').serialize(),
success: function(data) {
// do something
}
});

Jquery UI autocomplete and webservice

I have a ASP textbox of class clsArtistList placed inside a usercontrol
<asp:TextBox CssClass="clsArtistList" ID="txtArtistList" runat="server"></asp:TextBox>
Then I use jquery-ui-1.8.16 to create the autocomplete feature for my textbox. I copied it from http://www.dotnetcurry.com/ShowArticle.aspx?ID=515 but I don't really know how it works
$(".clsArtistList").autocomplete({
source: function(request, response) {
$.ajax({
url: "../ArtistWS.asmx/GetAllArtists",
data: "{ 'ARTIST_NAME': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.ARTIST_NAME
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
},
minLength: 1
});
and this is my web service
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<Artist> GetAllArtists(string ARTIST_NAME) {
ArtistCollection coll = ArtistManager.GetAllArtists();
return coll.FindAll(a => a.ARTIST_NAME.ToLower().StartsWith(ARTIST_NAME.ToLower()));
}
For your interests, my ArtistCollection is a List of artist. And an Artist class looks like this:
public class Artist {
public string ARTIST_ID { get; set; }
public string ARTIST_NAME { get; set; }
public string ARTIST_NATIONALITY { get; set; }
public string ARTIST_INFO { get; set; }
}
But the code does not work. Each time i type, I recieve a message alert Internal Server Error
Thank you in advance. I need you helps
If you receiver a server error message, I would assume the problem is not in the javascript, but somewhere on your server.
Did you try to debug your ASP webservice code?
I think the problem may be the value you are setting url to.
Try removing the ".." from the call
$.ajax({
url: "/ArtistWS.asmx/GetAllArtists",

Categories