jquery CALLING TO Services! Services.invoke - ajax

This a service function "GetTaskProgress":
[WebMethod]
public IList<OrderViewDTO> GetTaskProgress(DateTime xDATEx)
{
try
{
return new OrderDataRepository()
.GetAllOrderData()
.Where(x => x.POD_DATE == xDATEx)
.GroupBy(o => o.User)
.Select(g => new OrderViewDTO
{
DriverId = g.Key.Id,
PdriverName = g.Key.Name,
OrderCount = g.Count(),
OrderCountWhereNameIsNotNull = g.Count(o => o.RECEIVE_NAME != null)
})
.ToList();
}
catch (Exception e)
{
throw WrapException(e);
}
}
This is the code of the jquery load button:
$('#LoadButton').click(function () {
var DateTime = $('#DateInput').val();
if (DateTime == '')
{
alert('PLEASE ENTER DATE');
}
else {
_Services.invoke({
method: 'GetTaskProgress',
data: { DateTime: DateTime },
success: function () {
alert(DateTime);
How do I call GetTaskProgress with a jQuery function that will pass the "date" into xDATEx?
at the moment when i click on the button i have the bug Invalid web service call, missing value for parameter: 'xDATEx

I'm not sure about _Services.invoke() (analogous to $.ajax() perhaps?), but you probably need to change your data parameter to match your service method parameter. Try this
_Services.invoke({
method: 'GetTaskProgress',
data: { xDATEx: DateTime },
success: function () {
alert(DateTime);
}
});

Related

how i make a condition with ajax and asp mvc

I want to put a condition if the user want to add a second appointment he receives an alert
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
this is my code in controller :
public JsonResult SaveEvent(Event e)
{
var status = false;
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
status = true;
}
i want to make the user add one time his event and receive an alert i try but not work
I think i can help:
if(Session["appointment"] != "ok")<>
{
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.StartDate = e.StartDate;
v.EndDate = e.EndDate;
v.EventDescription = e.EventDescription;
v.EventID = e.EventID;
v.ThemeColor = e.ThemeColor;
}
else
db.Events.Add(e);
db.SaveChanges();
Session["appointment"] = "ok";
return JSON(new{appointment="ok"});
}
}else
{
return JSON(new {appointment="no-good");
}
and controller:
function SaveEvent(data)
{
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function(data) {
if (data.appointment == "ok")
{
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
else { your msg error here }
},
error: function() {
alert('Failed');
}
})
}
})
dont not forget Session.Clear();
as the user logs out

ASP.net cascading dropdown list

trying to implement country state dropdown in mvc but couldn't..
conotroller :-
[HttpGet]
public ActionResult GetCities(int StateId)
{
Business.Services.City cityService = new Business.Services.City();
List<Business.Models.City> stateList = cityService.GetCityByStateId(StateId);
//var jsonSerialiser = new JavaScriptSerializer();
//var json = jsonSerialiser.Serialize(stateList);
return Json(new { stateList }, JsonRequestBehavior.AllowGet);
}
method:
public List<Models.City> GetCityByStateId(int StateId)
{
try
{
var list = new List<SelectListItem>();
Collection<DBParameters> parameters = new Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "StateId", DBType = DbType.Int32, Value = StateId });
var city = this.ExecuteProcedure<Models.City>("GetCityByState", parameters).ToList();
//if (city != null && city.Count > 0)
//{
// list = city.Select(x => new SelectListItem { Text = x.CityName, Value = x.StateId.ToString() }).ToList();
//}
return city;
}
catch (Exception ex)
{
throw;
}
}
change event:
$('.ddlstate').change(function () {
debugger;
$.ajax({
url: '#Url.Action("GetCities", "User")',
type: "GET",
data: { StateId: $(this).val() },
dataType: "json",
success: function (result) {
debugger;
//alert(result.stateList[0].CityId);
$.each(result.stateList, function () {
debugger;
$('.cityddl').append($("<option></option>").val(CityId).html(CityName));
});
},
error: function (result, status, jQxhr) {
alert("Error: " + result + "-" + status + "-" + jQxhr);
}
});
});
i get count of the citites in method and controller but when i run project and change state dropdown i got blank city dropdown. what is wrong?
It looks like you're missing a couple of things in the $.each() call.
You should pass the JSON result from the ajax call to the $.each
You also need to provide a parameter to the callback function so that the callback function has something to work with
It could look something like this:
$.each(result.stateList, function(index, city) {
$('.cityddl').append($("<option></option>").val(city.CityId).html(city.CityName));
});

how to send serialized form to webapi Method

im trying to send my from with ajax( $.post ) to a webApi . ajax request run succesfull but when i send data to method in web api form collection get null then my method return "false"
please help me
My WebApi Method
[System.Web.Http.HttpPost]
public string AddRecord([FromBody]FormCollection form)
{
try
{
PersonBLL personbll = new PersonBLL();
var person = new tbl_persons();
person.firstname = form["txt_namePartial"];
person.lastname = form["txt_lastnamePartial"];
person.age = byte.Parse(form["txt_agePartial"]);
var result = personbll.AddRecord(person);
return result;
}
catch (Exception)
{
return "false";
}
}
my Ajax function
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",JSON.stringify(url) , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}
I often use that :
var form = $("#body").find("form").serialize();
$.ajax({
type: 'POST'
url: "/api/Person/AddRecord",
data: form,
dataType: 'json',
success: function (data) {
// Do something
},
error: function (data) {
// Do something
}
});
Get a try because I never used the FormCollection object type but just a model class.
This should be:
url=$("#form").serialize();
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",url , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}

returning different javascript object from controller

my controller action:
[HttpPost]
public ActionResult AddPointAndCopyOtherSongToPlaylist(int id)
{
if (CheckIfAddPointToSelf(User.Identity.Name, id))
{
var song = repository.GetSong(id);
foreach (var item in song.Points)
{
if (User.Identity.Name == item.UsernameGavePoint)
{
var data1 = 1;
return Json(new {data1}, JsonRequestBehavior.AllowGet);
}
}
var originalSong = repository.GetSong(id);
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = originalSong.Title;
newSong.YoutubeLink = originalSong.YoutubeLink;
newSong.GenreId = 38;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = originalSong.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.OtherSongId = id;
repository.AddPoint(point);
repository.Save();
int data = 2;
//process here
return Json(new { data }, JsonRequestBehavior.AllowGet);
}
else
{
return null;
}
}
based on different scenarios I want to return a javascript and somehow notify the client of what was returned and based in the result do something in the success part of my ajax call:
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyOtherSongToPlaylist/",
type: "POST",
data: { id: songId },
success: function (data,one) {
if (data && !one) {
HideAjaxLoader(), ShowMsg("Song Added Successfully");
}
else if(!data) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data && one) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
I tried many different variations but I think i need something like data.property1 returned and in the client to check if that property exists or soemthing like that.. please help
You need to return your status code within the object.
return Json( new { data1 = "Some Other Data", status = 1} );
Then in your success handler check data.status.
if (data.status === 1) {
alert(data.data1);
}

sending multiple parameters asp.net mvc jquery ajax

I get server error:status of 500 when I try to send 2 parameters to my action in a controller with jquery ajax, dont know why?
this is the jquery code:
$(".genreLinks").click(function () {
var genreId = $(this).attr("name");
var songId = $("#hiddenRank").val();
$.ajax({
beforeSend: function () { ShowAjaxLoader(); },
url: "/Home/AddPointAndCopyTopTenFavToPlaylist/",
type: "POST",
data: { id: songId, genre: genreId },
success: function (data) {
if (data.status === 1) {
HideAjaxLoader(), ShowMsg("Song Added Successfully")
}
else if (data.status === 4) {
HideAjaxLoader(), ShowMsg("you cannot add your own songs");
}
else if (data.status === 3) {
HideAjaxLoader(), ShowMsg("Cannot add the song. The song was most likely modified or Deleted, we advise you to refresh the page");
}
else if (data.status === 2) {
HideAjaxLoader(), ShowMsg("You cannot add the same song twice");
}
},
error: function () { HideAjaxLoader(), ShowMsg("Song could not be added, please try again") }
});
});
controller's action code that accepts two parameters from my request:
[HttpPost]
public ActionResult AddPointAndCopyTopTenFavToPlaylist(int id, int genre)
{
var song = repository.GetTopTenFav(id);
if (song != null)
{
if (!(song.UserName.ToLower() == User.Identity.Name.ToLower()))
{
foreach (var item in song.Points)
{
if (User.Identity.Name.ToLower() == item.UsernameGavePoint.ToLower())
{
return Json(new { status = 2 }, JsonRequestBehavior.AllowGet);
}
}
var newSong = new Song();
newSong.UserName = User.Identity.Name;
newSong.Title = song.Title;
newSong.YoutubeLink = song.YoutubeLink;
newSong.GenreId = genre;
newSong.Date = DateTime.Now;
repository.AddSong(newSong);
var point = new Point();
point.UsernameGotPoint = song.UserName;
point.UsernameGavePoint = User.Identity.Name;
point.Date = DateTime.Now;
point.Score = 1;
point.TopTenFavId = id;
repository.AddPoint(point);
repository.Save();
return Json(new { status = 1 }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { status = 4 }, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(new { status = 3 }, JsonRequestBehavior.AllowGet);
}
}
I have also registered my new route:
routes.MapRoute(
"AddPoint", // Route name
"{controller}/{action}/{songId},{genreId}", // URL with parameters
new { controller = "Home", action = "", songId = UrlParameter.Optional, genreId = UrlParameter.Optional } // Parameter defaults
);

Resources