how i make a condition with ajax and asp mvc - ajax

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

Related

How to add my textbox item in the table? in master detail form

I am using MVC to create my Master Detail form, i have tried this to add my detail record in the to show my detail record in the form so that when user click Add button detail data itself shows in a table.
JQUERY is not working
This is my View:
#section script{
//date picker
$(function () {
$('#orderDate').datepicker({
datepicker: 'mm-dd-yy'
});
});
$(document).ready(function()
{
var orderItems = [];
//Add Button click function
$('#add').click(function () {
//Chk Validation
var isValidItem = true;
if ($('#itemName').val().trim() == '') {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'vissible')
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden')
}
if (!($('#quantity').val().trim() !== '' && !isNaN($('#dvch_nar').val().trim()))) {
isValidItem = false;
$('#quantity').siblings('span.error').css('visibility', 'vissible')
}
else {
$('#quantity').siblings('span.error').css('visibility', 'hidden')
}
if (!($('#itemName').val().trim() !== '' && !isNaN($('#dvch_cr_amt').val().trim()))) {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'vissible')
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden')
}
if (!($('#rate').val().trim() !== '' && !isNaN($('#dvch_cr_amt').val().trim()))) {
isValidItem = false;
$('#rate').siblings('span.error').css('visibility', 'vissible')
}
else {
$('#rate').siblings('span.error').css('visibility', 'hidden')
}
//add item to list if valid
if (isValidItem) {
orderItems.push(
{
ItemName: $('#itemName').val().trim(),
Quantity:parseInt$('#quantity').val().trim(),
Rate: parseInt$('#rate').val().trim(),
Total: parseInt($('#quantity').val().trim())* parseFloat($('#rate').val().trim())
});
//clear fields
$('#itemName').val('').focus();
$('#quantity').val('');
$('#rate').val('');
}
//populate order item
GeneratedItemsTable();
}
);
//save button click function
$('#submit').click(function () {
//validation order
var isAllValid = true;
if(orderItems.length=0)
{
$('#orderItems').html('<span style="color:red;">Please add another item</span>')
isAllValid = false;
}
if ($('#orderNo').val().trim() == '')
{
$('#orderNo').siblings('span.error').css('visibility', 'visible')
isAllValid = false;
}
else {
$('#orderNo').siblings('span.error').css('visibility', 'hidden')
}
if ($('#orderDate').val().trim() == '') {
$('#orderDate').siblings('span.error').css('visibility', 'visible')
isAllValid = false;
}
else {
$('#orderDate').siblings('span.error').css('visibility', 'hidden')
}
//if ($('')
//save if valid
if (isAllValid){
var data={
Date: $('#orderNo').val().trim(),
Remarks: ('#orderDate').val().trim(),
Description:$('description').val().trim(),
orderDetails:orderItems
}
}
$(this).val("Please Wait...");
$.ajax(
{
url: "/Home/SaveOrder",
type:"post",
data:JSON.stringify(data),
dataType:"application/json",
success:function(d){
//check is successfully save to database
if(d.status==true)
{
//will send status from server side
alert('successfully done.');
//clear form
orderItems=[];
$('#orderNo').val('');
$('#orderDate').val('');
$('#orderItems').empty();
}
else{
alert('Failed');
}
},
error :function(){
alert('Error:Please Try again.');
}
}
);
});
//function for show added item
function GeneratedItemsTable()
{
if(orderItems.length>0)
{
var $table = $('<table/>');
$table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th></tr></thead>')
var $tboday = $('<tbody/>');
$.each(orderItems,function(i,val)
{
var $row=$('<tr/>');
$row.append($('<tr/>').html(val.ItemName))
$row.append($('<tr/>').html(val.Quantity))
$row.append($('<tr/>').html(val.Rate))
$row.append($('<tr/>').html(val.Total))
$tboday.append($row);
});
$table.append($tboday);
$('#orderItems').html($table);
}
}
}
);
</script>
}
thanks for quick response
Try this
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
//Date Picker
$(function () {
$('#orderDate').datepicker({
dateFormat : 'mm-dd-yy'
});
});
$(document).ready(function () {
var orderItems = [];
//Add button click function
$('#add').click(function () {
//Check validation of order item
var isValidItem = true;
if ($('#itemName').val().trim() == '') {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'visible');
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#quantity').val().trim() != '' && !isNaN($('#quantity').val().trim()))) {
isValidItem = false;
$('#quantity').siblings('span.error').css('visibility', 'visible');
}
else {
$('#quantity').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#rate').val().trim() != '' && !isNaN($('#rate').val().trim()))) {
isValidItem = false;
$('#rate').siblings('span.error').css('visibility', 'visible');
}
else {
$('#rate').siblings('span.error').css('visibility', 'hidden');
}
//Add item to list if valid
if (isValidItem) {
orderItems.push({
ItemName: $('#itemName').val().trim(),
Quantity: parseInt($('#quantity').val().trim()),
Rate: parseFloat($('#rate').val().trim()),
TotalAmount: parseInt($('#quantity').val().trim()) * parseFloat($('#rate').val().trim())
});
//Clear fields
$('#itemName').val('').focus();
$('#quantity,#rate').val('');
}
//populate order items
GeneratedItemsTable();
});
//Save button click function
$('#submit').click(function () {
//validation of order
var isAllValid = true;
if (orderItems.length == 0) {
$('#orderItems').html('<span style="color:red;">Please add order items</span>');
isAllValid = false;
}
if ($('#orderNo').val().trim() == '') {
$('#orderNo').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#orderNo').siblings('span.error').css('visibility', 'hidden');
}
if ($('#orderDate').val().trim() == '') {
$('#orderDate').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#orderDate').siblings('span.error').css('visibility', 'hidden');
}
//Save if valid
if (isAllValid) {
var data = {
OrderNo: $('#orderNo').val().trim(),
OrderDate: $('#orderDate').val().trim(),
//Sorry forgot to add Description Field
Description : $('#description').val().trim(),
OrderDetails : orderItems
}
$(this).val('Please wait...');
$.ajax({
url: '/Home/SaveOrder',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
//clear form
orderItems = [];
$('#orderNo').val('');
$('#orderDate').val('');
$('#orderItems').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#submit').val('Save');
}
});
}
});
//function for show added items in table
function GeneratedItemsTable() {
if (orderItems.length > 0)
{
var $table = $('<table/>');
$table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th><th></th></tr></thead>');
var $tbody = $('<tbody/>');
$.each(orderItems, function (i, val) {
var $row = $('<tr/>');
$row.append($('<td/>').html(val.ItemName));
$row.append($('<td/>').html(val.Quantity));
$row.append($('<td/>').html(val.Rate));
$row.append($('<td/>').html(val.TotalAmount));
var $remove = $('Remove');
$remove.click(function (e) {
e.preventDefault();
orderItems.splice(i, 1);
GeneratedItemsTable();
});
$row.append($('<td/>').html($remove));
$tbody.append($row);
});
console.log("current", orderItems);
$table.append($tbody);
$('#orderItems').html($table);
}
else {
$('#orderItems').html('');
}
}
});
</script>

How to make the search case insensitive in Jsgrid filter?

I am trying to make the search case insensitive, and I have tried all the solutions that are found in issues, but it's still not working. Here is the code that I have right now, but I want it to be able to search regardless if user types in letters with uppercase or lowercase.
loadData: function (filter) {
criteria = filter;
var data = $.Deferred();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Admin/getMultiCentreDeals",
dataType: "json"
}).done(function (response) {
var res = [];
if (criteria.dealTitle !== "") {
response.forEach(function (element) {
if (element.dealTitle.indexOf(criteria.dealTitle) > -1) {
res.push(element);
response = res;
}
}, this);
}
else res = response;
if (criteria.dealSubTitle !== "") {
res = [];
response.forEach(function (element) {
if (element.dealSubTitle.indexOf(criteria.dealSubTitle) > -1)
res.push(element);
}, this);
}
else res = response;
if (criteria.dealURL !== "") {
res = [];
response.forEach(function (element) {
if (element.dealURL.indexOf(criteria.dealURL) > -1)
res.push(element);
}, this);
}
else res = response;
data.resolve(res);
});
return data.promise();
},
},
case in-sensitive search:
loadData: function(filter) {
return $.grep(this.items, function(items) {
return !filter.name||
(items.name.toLowerCase().indexOf(filter.name.toLowerCase()) > -1);
});
}
var res = [];
if (criteria.HotelName !== "") {
response.forEach(function (element) {
if (element.HotelName.toLowerCase().indexOf(criteria.HotelName.toLowerCase()) > -1) {
res.push(element);
response = res;
}
}, this);
}
else res = response;

AJAX error return ModelState Error

On my Create page I am using ajax and calling my api controller when creating a person:
<script>
$(document).ready(function() {
var newUrl = '#Url.Action("Index", "PersonInformations")';
var settings = {};
settings.baseUri = '#Request.ApplicationPath';
var infoGetUrl = "";
if (settings.baseUri === "/ProjectNameOnServer") {
infoGetUrl = settings.baseUri + "/api/personinformations/";
} else {
infoGetUrl = settings.baseUri + "api/personinformations/";
}
$("#Create-Btn").on("click",
function(e) {
$("form").validate({
submitHandler: function () {
e.preventDefault();
$.ajax({
method: "POST",
url: infoGetUrl,
data: $("form").serialize(),
success: function () {
toastr.options = {
onHidden: function () {
window.location.href = newUrl;
},
timeOut: 3000
}
toastr.success("Individual successfully created.");
},
error: function (jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
var error = $.parseJSON(jqXHR.responseText);
//console.log(jqXHR.responseText);
toastr.error(status + " - " + error.message);
}
});
}
});
});
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
});
</script>
Here is the method in my PersonInformations API controller:
[ResponseType(typeof(PersonInformation))]
public IHttpActionResult PostPersonInformation(PersonInformation personInformation)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var lstOfPersons = db.PersonInformations.Where(x => x.deleted == false).ToList();
if (lstOfPersons.Any(
x =>
x.FirstName == personInformation.FirstName && x.LastName == personInformation.LastName &&
x.AId == personInformation.AgencyId && x.ID != personInformation.ID))
{
ModelState.AddModelError("", "This person already exists!");
return BadRequest(ModelState);
}
if (
lstOfPersons.Any(
x => x.Email.ToLower() == personInformation.Email.ToLower() && x.ID != personInformation.ID))
{
ModelState.AddModelError(personInformation.Email, "This email already exists!");
return BadRequest(ModelState);
}
personInformation.FirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(personInformation.FirstName);
personInformation.LastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(personInformation.LastName);
db.PersonInformation.Add(personInformation);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = personInformation.ID }, personInformation);
}
Now when I test this and purposely enter an email that already exists, the ajax request errors out but returns the message:
Error - The Request is invalid
but when I use console.log(jqXHR.responseText)
I get this:
Create
{
"$id": "1",
"message": "The request is invalid.",
"modelState": {
"$id": "2",
"test#test.com": [
"This email already exists!"
]
}
}
How do I get the "This email already exists!" as the error message?
I just figured this out. I know that the modelState was an array type, and the 2nd value was the actual email address entered.
So I edited my button.click event to this:
$("#Create-Btn").on("click",
function(e) {
$("form").validate({
submitHandler: function () {
e.preventDefault();
var emailValue = $("#Email").val();
$.ajax({
method: "POST",
url: infoGetUrl,
data: $("form").serialize(),
success: function () {
toastr.options = {
onHidden: function () {
window.location.href = newUrl;
},
timeOut: 3000
}
toastr.success("Individual successfully created.");
},
error: function (jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
var error = $.parseJSON(jqXHR.responseText);
toastr.error(status + " - " + error.modelState[emailValue]);
}
});
}
});
});
Find the error message via array bracket notation along with getting the actual value of the email trying to be submitted did the trick.

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