I'm using FullCalendar (http://arshaw.com/fullcalendar/) and I need help with passing data using json to a c# function in the code behind page of my ASP.net page.
I am using json to load data like so in my FullCalendar web application:
Code behind:
[WebMethod]
public static List<Event> GetEvents()
{
List<Event> events = new List<Event>();
events.Add(new Event()
{
EventID = 1,
EventName = "EventName 1",
StartDate = DateTime.Now.ToString("MM-dd-yyyy"),
EndDate = DateTime.Now.AddDays(2).ToString("MM-dd-yyyy"),
EventColor = "red"
});
events.Add(new Event()
{
EventID = 2,
EventName = "EventName 2",
StartDate = DateTime.Now.AddDays(4).ToString("MM-dd-yyyy"),
EndDate = DateTime.Now.AddDays(5).ToString("MM-dd-yyyy"),
EventColor = "green"
});
return events;
}
asp.x page:
events: function(start, end, callback)
{
$.ajax(
{
type: 'POST',
contentType: 'application/json',
data: "{}",
dataType: 'json',
url: "Calendar.aspx/GetEvents",
cache: false,
success: function (response) {
var events = $.map(response.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.end = new Date(item.EndDate);
event.title = item.EventName;
event.color = item.EventColor;
return event;
})
callback(events);
},
error: function (err) {
alert('Error');
}
});
},
This is working fine. Now I want to save data by calling a function and passing it data. Here is what I have done so far:
Code behind:
[WebMethod]
public static bool SaveEvents(List<Event> events)
{
//iterate through the events and save to database
return true;
}
asp.x page
function save() {
var eventsFromCalendar = $('#calendar').fullCalendar('clientEvents');
var events = $.map(eventsFromCalendar, function (item, i) {
var event = new Object();
event.id = item.id;
event.start = item.start;
event.end = item.end;
event.title = item.title;
event.color = item.color;
return event;
});
$.ajax(
{
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(events), **<-- I have to pass data here but how???**
dataType: 'json',
url: "Calendar.aspx/SaveEvents",
cache: false,
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
return false;
}
The above ajax post is where I need help with. The variable events contais all the FullCalendar event info.
How do I pass the data 'events' to the function 'SaveEvents'?
I can change the SaveEvents signature if need be.
EDIT
If I change my c# function to use an array like s0:
[WebMethod]
public static bool SaveEvents(Event[] newEvents)
{
return true;
}
And pass the following data through:
data: JSON.stringify({ newEvents: events }),
Then the function 'SaveEvents' gets called with an array of size 4 but all the data values are null, why is this?
Thanks
Obvious from your code that you have a c# class as
public class Events
{
public int EventID {get; set;}
public string EventName {get;set;}
public StartDate {get; set;}
public string end {get; set;}
public string color {get; set;}
}
So take json array. A sample here
// Array which would be provided to c# method as data
var newEvents=[
{
EventID : 1,
EventName : "EventName 1",
StartDate : "2015-01-01",
EndDate : "2015-01-03",
EventColor : "red"
},
{
EventID : 2,
EventName : "EventName 2",
StartDate : "2015-01-02",
EndDate : "2015-01-04",
EventColor : "green"
}
];
Now the ajax request which passes JSON objects to posted URL
$.ajax
({
type: 'POST',
contentType: 'json',
data: {newEvents:newEvents},// Pass data as it is. Do not stringyfy
dataType: 'json',
url: "Calendar.aspx/SaveEvents"
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
Update :
To make sure that there is nothing else wrong please test your Save Events as. If it goes fine above should work as well, As it is working for me :)
[WebMethod]
public static bool SaveEvents(string EventName)
{
//iterate through the events and save to database
return true;
}
$.ajax
({
type: 'POST',
contentType: 'json',
data: {EventName:'myevet 1'},
url: "Calendar.aspx/SaveEvents",
cache: false,
success: function (response) {
alert('Events saved successfully');
},
error: function (err) {
alert('Error Saving Events');
}
});
Related
I'm trying to implement file download functionality thru ajax call in MVC.
After calling of controller method i always have a "parseerror", can somebody explain me why?
my ajax:
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
$.ajax({
type: "POST",
url: "/File/FileDownload",
//contentType: false,
//processData: false,
//dataType: "json",
data: { fileId: id },
success: function (data) {
$('#uploadStatus').html("ok");
},
error: function (err) {
alert(err.statusText);
}
});
});
and controller:
[HttpPost]
public FileResult FileDownload(int? fileId)
{
FileDBEntities db = new FileDBEntities();
tblFile file = db.tblFiles.ToList().Find(p => p.id == fileId.Value);
return File(file.Data, file.ContentType, file.Name);
}
with simple download link in razor it works, but not with ajax.
What am I doing wrong here?
Why not simple use
tab.on("click", ".FileDownload", function (e) {
//$('#uploadStatus').html("ok");
var tr = $(this).closest("tr");
var id = tr.data("id");
window.location = window.location.origin + '/File/FileDownload?fileId=' + id;
});
[HttpGet]
public FileResult FileDownload(int? fileId)
I am working with a custom workflow solution that I am creating. I would like to create a postback that has the model, and two integer values that represent the action and step that I have completed. I don't want to add them to the model because they are only used in this one place. The signature for this postback would be something like this.
[HttpPost]
public void ProcessWorkflowAction(EditScreenModelValidation model, int stepActionId, int stepNumber)
{
//Some work on model and actions
}
I would really like to do this through JS because that is currently how I am getting StepActionId and StepId. Is there a way to package up the model to send through JS?
var modelObj = CreateModelData();
var postObj = JSON.stringify(modelObj);
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
url: "url",
data: { model: modelObj, stepActionId: stepId, stepNumber: 3 }
cache: false,
complete: function (data) {
}});
CreateModelData = function () {
var modelObj = {};
var modelArray = $('#frm').serializeArray()
$.each(modelArray, function (index, value) {
assign(modelObj, value.name, value.value);
})
return modelObj;
};
function assign(obj, prop, value) {
if (prop != undefined) {
if (typeof prop === "string")
prop = prop.split(".");
if (prop.length > 1) {
var e = prop.shift();
assign(obj[e] =
Object.prototype.toString.call(obj[e]) === "[object Object]"
? obj[e]
: {},
prop,
value);
} else
obj[prop[0]] = value;
}
}
The model comes back as null in the controller. I have also tried the following code with the same result.
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
url: "url",
data: { model: $('#frm').serializeArray(), stepActionId: stepId, stepNumber: 3 }
cache: false,
complete: function (data) {
}});
You need to build up the object, assign the properties (make sure it matches any model validation and the field names are the same as your model) and use JSON.stringify to make the conversion:
var modelObj = {};
modelObj.prop1 = $('#txtField1').val();
modelObj.prop2 = $('#txtField2').val();
// etc... make sure the properties of this model match EditScreenModelValidation
var postObj = JSON.stringify(modelObj); // convert object to json
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
url: "/Workflow/Home/ProcessWorkflowAction",
data: { model: postObj, stepActionId: stepId, stepNumber: 3 }
cache: false,
complete: function (data) {
if (data.responseText.length > 0) {
var values = $.parseJSON(data.responseText)
$('#ActionErrors').html(values.message)
}
else {
location.reload();
}
}});
It's possible and pretty easy to do. MVC is nice about packaging up what you send it.
So if your model looks like:
public class TestModel
{
public string Name { get; set; }
public int Age { get; set; }
}
And your post method looks like:
[HttpPost]
public void TestMethod(TestModel model, int num1, int num2)
{
// Stuff
}
Your javascript POST would look like:
function doPost(){
$.post("/Home/TestMethod",
{
model: {
Name: "Joe",
Age: 29
},
num1 : 5,
num2 : 10
},
function (data, status) {
//Handle status if you decide to return something
});
}
Hope that helps!
So here is how I got it to work. The CreateModelData uses the (frm).serializeArray() method, but I found that if the item was disabled or not on the page, then it didn't create that property.
var modelObj = CreateModelData();
var postObj = JSON.stringify(modelObj);
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
url: "url",
data: { modelString: postObj, stepActionId: stepId, stepNumber: 3 },
cache: false,
complete: function (data) {
}});
});
CreateModelData = function () {
var modelObj = {};
var modelArray = $('#frm').serializeArray();
$.each(modelArray, function (index, value) {
assign(modelObj, value.name, value.value);
})
return modelObj;
};
function assign(obj, prop, value) {
if (prop != undefined) {
if (typeof prop === "string")
prop = prop.split(".");
if (prop.length > 1) {
var e = prop.shift();
assign(obj[e] =
Object.prototype.toString.call(obj[e]) === "[object Object]"
? obj[e]
: {},
prop,
value);
} else
obj[prop[0]] = value;
}
}
On the controller side, I changed the signature to be all string values like so.
[HttpPost]
public void ProcessWorkflow(string modelString, int stepActionId, int stepNumber)
{
}
To make the modelString value the actual model object, I did this.
using (Stream s = GenerateStreamFromString(json))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(modelObj));
return (modelObj)serializer.ReadObject(s);
}
In the end, this worked for me. All the fields were there and I got no errors. When i tried to have the first variable in the controller method to be the model object, it always came back as null for me no matter what I did.
The fastest and easiest way to get all the fields in the Model is to serialize the Form which is bound with Model.
Update
The problem that you were receiving null in properties is because serializeArray() create key value format json. you just need to get re-build the json from key value to Property value that can be mapped to the model.
var modelObj = $('#formId').serializeArray()
.reduce(function (a, x) { a[x.name] = x.value; return a; }, {});
A little tweak in you ajax call instead of datatype use contentType. This is another reason you were getting null in controller's model object parameter.
$.ajax({
type: "post",
url: "/Account/RegisterSome",
data: { model: modelobj, id: 3 },
contentType: 'application/json',
cache: false,
complete: function (data) {
}
});
I resolved the issue by removing the JSON.stringify() and just posting my javascript object.
I can't for the life of me understand why this code isn't working. I need a second set of eyes to review it - TIA:
This function returns success, but the C# method is not called.
JavaScript
$(function() {
($("#survey").on("submit", function() {
var data = serializeForm();
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert('ok');
},
error: function(data) {
alert('failed');
}
}); //ajax
return false;
}));
function serializeForm() {
var data = new Object;
$("#survey input[type='checkbox']").each(
function(index) {
data[$(this).get(0).id] = $(this).get(0).checked ? 1 : 0;
});
data.otherEnviron = $("#survey input[type='text']").val();
var strData = JSON.stringify(data);
return strData;
}
});
Revised:
$(function () {
($("#survey").on("submit", function() {
var data = serializeForm();
alert(data);
$.ajax({
type: "POST",
url: "Default.aspx/SaveSurveyInfo",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('ok-'+ data);
},
error: function (xml, textStatus, errorThrown) {
alert(xml.status + "||" + xml.responseText);
}
}); //ajax
return false;
}));
Note:
strData="{\"ms\":1,\"google\":0,\"PHP\":0,\"otherEnviron\":\".NET\"}"
C# WebMethod
[WebMethod]
private void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
using (SqlConnection scon = new SqlConnection(connectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
}
}
Revised C#
[WebMethod]
public static void SaveSurveyInfo(int ms, int google, int PHP, string otherEnviron)
{
try
{
using (SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["C287577_NorthwindConnectionString"].ConnectionString))
{
scon.Open();
SqlCommand scmd = scon.CreateCommand();
scmd.CommandType = System.Data.CommandType.StoredProcedure;
scmd.CommandText = "SurveyResults";
scmd.Parameters.AddWithValue("MicrosoftTranslator", ms);
scmd.Parameters.AddWithValue("GoogleTranslator", google);
scmd.Parameters.AddWithValue("PHPOkay", PHP);
scmd.Parameters.AddWithValue("other", otherEnviron);
scmd.ExecuteNonQuery();
scmd.Dispose();
}
} catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
This is still not working. No error msg is shown, only ok.
because WebMethod must be public and static
Similar question: ASP.NET jQuery error: Unknown Web Method
If you need more security around your ajax call, try moving it to a web service.
public static void SaveSurveyInfo
The method should be static and public in aspx pages to be hit.
In asmx it can be just public.
I am new working with jquery ajax calls in fact my first time and, I am running into a issue here my web service is working but for some reason when I try to call it from jquery ajax the data is not retrieve.
Please I've been working the whole day on this and I need to finish it tonight.
My web method is this :
public Didyoumean SayHello(string search)
{
Didyoumean Didyoumean = new Didyoumean();
string cs = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand ("USP_DidYouMean",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#search",search);
cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Didyoumean.SearchInput = reader["detail"].ToString();
}
reader.Close();
con.Close();
}
return Didyoumean;
}
my Didyoumean class is this:
public class Didyoumean
{
public string SearchInput { get; set; }
}
my ajax call is this (the error is most likely to be here)
function bla() {
var SearchInput = document.getElementById("#locationSearchInput").value;
var DataObject = { search: SearchInput };
$.ajax({
type: "POST",
url: "/kiosk/EmailCoupon.asmx/SayHello",
data: JSON.stringify({dataObject}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.tags_select a').html(data.d);
},
error: function () {
$('.tags_select a').html("<p>no suggestion</p>")
}
});
}
and finally my html
<input id="Button1" type="button" value="button" onclick="bla()"/>
<div class="tags_select">
Basically what I am trying to do is depending on the data in my database the application give suggestions for spelling errors.
note: do not pay attention to the name of the functions and methods this is just a test.
Your service might be like this
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public Didyoumean SayHello(string search)
{
Didyoumean didyoumean = new Didyoumean();
didyoumean.searchInput = "result of " + search;
return didyoumean;
}
}
and your javascript is
function test() {
var SearchInput = "test";
$.ajax({
type: "POST",
url: "/WebService1.asmx/SayHello",
data: JSON.stringify({search:SearchInput}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var didYouMean = data.d;
alert(didYouMean.searchInput);
},
error: function (e) {
console.log(e);
}
});
}
I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>