Here is my C# code:
if (!String.IsNullOrEmpty(bookRoom))
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); //If we ever upgrade, its not that important but change this to the right version
//service.UseDefaultCredentials = true;
service.Credentials = new WebCredentials("MYNLJ", "", "");
service.Url = new Uri("http://DIR/EWS/Exchange.asmx"); //This is the EWS file
Appointment appointment = new Appointment(service);
String ITMtgMailboxToAccess = roomEmail; //Mailbox name
FolderId ITMtgCalendarFolderId = new FolderId(WellKnownFolderName.Calendar, ITMtgMailboxToAccess);
appointment.Subject = "Walk In Meeting";
appointment.Body = "Test Meeting";
double htoAdd = Convert.ToDouble(MeetingLength.SelectedItem.Value);
appointment.Start = DateTime.Now;
appointment.End = DateTime.Now.AddMinutes(htoAdd);
CalendarView Checkcv = new CalendarView(appointment.Start, appointment.End); //Don't change this
try
{
FindItemsResults<Appointment> ITMtgfapts = service.FindAppointments(ITMtgCalendarFolderId, Checkcv);
List<Appointment> ITMtgappointments = new List<Appointment>();
if (ITMtgfapts.Items.Count > 0) // If there is more than one item
{
Here I want to let the ajax request know that the booking wasn't successful
// "Your booking will conflict with another appointment";
}
else
{
Let the ajax request know it was successful
//Success
appointment.RequiredAttendees.Add(roomEmail);
appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
}
}
catch
{
}
}
AJAX code:
<script type="text/javascript">
$(function () {
$('#BookButton').click(function (event) {
var form = $('#Form1');
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: $("#BookRoom :input").serialize()
}).done(function () {
// Optionally alert the user of success here...
$('#BookRoom').modal('hide');
$('#SuccessMsg').text('Meeting Booked');
$('#SuccessMessage').modal('show');
setTimeout(function () { $('#SuccessMessage').modal('hide'); }, 3000);
}).fail(function () {
// Optionally alert the user of an error here...
alert("Error submitting AJAX request");
});
event.preventDefault(); // Prevent the form from submitting via the browser.
});
});
My advice is to respond an enum-value. The advantage is the scalability:
C#
public enum ReponseType : int
{
Success: 0,
InvalidInput: 1,
ServerError: 2,
....
}
Javascript
var ResponseType = {
Success: 0,
InvalidInput: 1,
ServerError: 2,
....
}
On the server:
return base.Json(ReponseType.Success);
// or return base.Json(ReponseType.InvalidInput);
// or return base.Json(ReponseType.ServerError);
On the client:
$.ajax({
...
}).done(function (data) {
if (data === ResponseType.Success) {
// Notify user: Success
}
else if (data === ResponseType.InvalidInput) {
// Notify user: It is his fault
}
else if (data === ResponseType.ServerError) {
// Notify user: It is your fault
}
});
Related
I have implemented Cascading (Dependent) DropDownList using ASP.NET MVC.
This is the tutorial
Now I need show alert message box after insert data and redirect on Index page in ASP.NET MVC.
To show alert message in ASP.NET MVC after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "#Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "#Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...
How to do resolve this?
Thanks.
Update 2021-01-02
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("User Details Inserted Successfully");
var url = "#Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#thedate").datepicker(options);
$(function () {
$(".loading").hide();
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#TicketId");
DisableDropDown("#CityId");
dropDownId = "#TicketId";
list = response.Ticket;
PopulateDropDown("#TicketId", list);
break;
case "TicketId":
list = response.States;
DisableDropDown("#StateId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
dropDownId = "#CityId2";
list = response.Cities2;
PopulateDropDown("#CityId2", list);
$("#GPS").val(response.GPS);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
</script>
}
update controller
[HttpPost]
public ActionResult Index(PersonModel person)
{
MTsqlinsert(person); //Insert values in the database
if (ModelState.IsValid)
{
PersonModel personModel = new PersonModel();
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
ViewData["result"] = "1";
return RedirectToAction("Index");
}
return View(person);
}
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
PersonModel personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}
I am trying to export selected records in to a file and reload the page to update the records in a current view. I am calling web api asynchronously to get all the records. An AJAX call is executing an action in a controller successfully and returning expected data without any error but none of the 'success', 'complete' or 'error' part of ajax function is executing. There are no errors in a developer tool of the browser, no exception, nothing unusual so its getting trickier for me to investigate this issue further. Can I request your a suggestions on this please? Thanks
View :
#Html.ActionLink("Export records", "Index", null, new { Id = "myExportLinkId")
Script :
$("a#myExportLinkId").click(function (e) {
var selected = "";
$('input#myCheckBoxList').each(function () {
if (this.checked == true) {
selected += $(this).val() + ',';
}
});
if (selected != "") {
$.ajax({
url: '/MyController/MyAction',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
'MyString': 'stringValue'
},
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
})
And the action/method looks like this :
[HttpGet]
public async Task<ActionResult> ExportNewOrders(string OrderIdString)
{
//code to create and store file
//actually want to send the file details as json/jsonResult but for testing only returning
//string here
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
}
Finally I have resolved this with Promisify functionality of an AJAX call. Obviously the json response I was returning had an issue so I have replaced
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
to
return new JsonResult(){
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
which has fixed the bug and the success function of ajax call got executed.
But other than this there were issues to wait until the file download (which involved encryption decryption, server validations etc) completes and then refresh the page. This I have resolved by implementing an ajax call with Promisify fuctionality. You can find codepen example here and the original post here.
Here is the complete code.
View/HTML
#Html.ActionLink("Export", "yourActionName", null, new { Id = "exportRequest", #onclick = "letMeKnowMyFileIsDownloaded();" })
Script/Ajax
function letMeKnowMyFileIsDownloaded() {
return new Promise(function (resolve, reject) {
$("a#exportRequest").on("click", function () {
$.ajax({
url: this.href + "?param=whatever params you want to pass",
dataType: "json",
data: {
'param1': 'value'
},
success: function (data) {
var a = document.createElement("a");
var url = '/yourControllerName/Download?fileGuid=' + data.guid + '&filename=' + data.fileName;//window.URL.createObjectURL(data);
a.href = url;
a.download = data.fileName;
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
resolve(true);
},
error: function (error) {
reject(error);
}
});
});
});
}
letMeKnowMyFileIsDownloaded()
.then(function (bool) {
if (bool) {
//alert("File downloaded 👇");
window.location.reload(1);
}
})
.catch(function (error) {
alert("error");
});
I have used nuget package ClosedXML to handle excel file functionality. Using the stream to create and download the data in excel file without storing the file physically on the server.
And in the controller
//can be async or sync action
public async Task<ActionResult> Index(YourModel model)
{
//do stuff you want
var exportOrders = your_object;
//using DataTable as datasource
var dataSource = new DataTable();
//write your own function to convert your_object to your_dataSource_type
dataSource = FormatTypeToDataTable(exportOrders);
if (dataSource != null && dataSource.Rows.Count > 0)
{
//install ClosedXML.Excel from nuget
using (XLWorkbook wb = new XLWorkbook())
{
try
{
var handle = Guid.NewGuid().ToString();
wb.Worksheets.Add(dataSource, "anyNameForSheet");
string exportFileName = "yourFileName" + ".xlsx";
MemoryStream stream = GetStream(wb);
TempData[handle] = stream; exportFileName);
return new JsonResult()
{
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
catch (Exception ex)
{
//ModelState.AddModelError("", ex.Message);
}
}
}
}
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
var stream = TempData[fileGuid] as MemoryStream;
var data = stream.ToArray();
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
return new EmptyResult();
}
}
I have written a WCF service which in theory, should accept a JSON object from Ajax and return true or false as a response to indicate the JSON object was accepted from service and sent to the database.
This is how the interface is implemented in IService
[OperationContract]
[WebInvoke(Method ="POST",ResponseFormat=WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json,UriTemplate ="InsertPatient")]
String InsertPatient(Patient PatientObj);
The contract is implemented as follows
public String InsertPatient(Patient PatientObj)
{
PatientContext pat = new PatientContext();
Boolean boolObj = new Boolean();
string JsonString = "";
if (pat.Patients.Where(x => x.Username == PatientObj.Username).Any())
{
// Username already taken;
boolObj = false;
JsonString =JsonConvert.ToString(boolObj);
return JsonString;
}
else
{ //Initiate to add user to login table
Login log = new Login();
log.Username = PatientObj.Username;
log.Password = PatientObj.Password;
log.User_Type = PatientObj.User_Type;
if (InsertLogin(log)) //if login added
{
pat.Patients.Add(PatientObj); //add user to patient table
pat.SaveChanges();
boolObj = true;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
else //login was not added
{
boolObj = false;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
}
}
and finally the Ajax script is implemented as follows
<script>
$(document).ready(function () {
$("form").submit(function () {
var L_Username = $("#UN").val();
var L_User_Type = "patient";
var L_Name = $("#name").val();
var L_Birthday = $("#bday").val();
var L_Gender = $("input[name='optradio']:checked").val();
var L_Contact = $("#cNo").val();
var L_Password = $("#password").val();
var L_Address = $("#adress").val();
var jsondata = {
Username: L_Username,
User_Type: L_User_Type,
Address: L_Address,
Birthday: L_Birthday,
Contact: L_Contact,
Gender: L_Gender,
Name: L_Name,
Password: L_Password
};
console.log(JSON.stringify(jsondata));
$.ajax({
url: "http://localhost:50709/Service1.svc/rest/InsertPatient",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(jsondata),
success: function (resultdata) {
alert("inserted");
},
error: function (e) {
alert("Something went wrong");
}
});
});
});
</script>
When I test this through POST-man , I get the correct response as true or false. But when I run this from the website itself. Ajax always throw the error alert, but the values get successfully added to the tables.
What am I doing wrong , please help. Thank you in advance.
I want to get page id from Facebook on custom page tab click. Here is the code, i am working with. Is this right way to get page id from the Facebook. I am able to get access token and user id values using this code. Any help is greatly appreciated.
window.fbAsyncInit = function () {
FB.init({
appId: 'xxxxxxxxx',
status: true,
cookie: true,
xfbml: true
});
FB.Event.subscribe('auth.authResponseChange', function (response) {
// Here we specify what we do with the response any time this event occurs.
if (response.status === 'connected') {
} else if (response.status === 'not_authorized') {
//FB.login();
} else {
//FB.login();
}
});
};
// Load the SDK asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
$('.btnclick').click(function () {
fblogin();
});
function fblogin() {
//FB.login();
FB.login(function (response) {
if (response.authResponse) {
var sq = FB.getAuthResponse()['signedRequest'];
var data = sq.split('.')[1];
data = JSON.parse(atob(data));
alert(data);
} else {
alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'user_location,user_hometown,user_photos,friends_photos,friends_location,friends_hometown,email,user_likes,publish_actions,manage_pages', display: 'popup' });
}
Step 1 : get manage_pages permission
step 2 :
FB.api('/me?fields=accounts', function (apiResponse) {
//apiResponse will have page id inside apiResponse.accounts.data
});
'/me?fields=accounts' - account is used to get fb pageid
For Getting page Detail form page id
FB.api('/ page id ?fields=about,albums{link},photos{link},phone,location,single_line_address', function (page) {
//To get page details from page id
});
i have a html button with "button-account" name in html body and want update aspx page with ajax when user click the button
I get this error in google chrom
SyntaxError: JSON.parse: unexpected character
and this in fire fox
SyntaxError: JSON.parse: unexpected character
Here's my Code
<script type="text/javascript" >
$(document).ready(function () {
$("#button-account").bind("click", "accountRegister");
function accountRegister() {
var waitObj = "<span class='wait' > <img src='Resource/Images/loading.gif' alt='' /> </span>";
var user = $("[name='username']").val();
var pass = $("[name='password']").val();
var dataObj = {
"username": user,
"password": pass,
};
$.ajax({
type: "POST",
url: "Checkout.aspx/login",
data: dataObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforSend: function () {
$(this).attr("disabled", "true");
$(this).after(waitObj);
},
success: function (msg) {
// Replace the div's content with the page method's return.
alert("success");
$("#checkout").slideUp("slow");
$("#payment-address").slideDown("slow");
},
error: function (msg) {
alert("error");
},
complete: function () {
$(this).attr("disabled", "false");
$(".wait").remove();
},
});
}
});
</script>
and here's my webmethod
[WebMethod]
public static string login()
{
//bool UserIsValid = false;
//string userName = "";
//string pass = "";
//MembershipUser u = Membership.GetUser(userName);
//pass = u.GetPassword();
//if (UserIsValid)
//{
// // returnAsHtml = "true";
//}
//else
//{
// //returnAsHtml = "use is not valid";
//}
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize("{ a:'1' }");
return result;
}
and fiddler return 200 status.
but return html. i know this is my mistake. how solve it?
any help is appriciate...
The server probably returns an error-page (e.g. "<html> ...") instead of the JSON response you expected.
Use fiddler, chrome's developer tools or a similar tool to check what the exact answer is, that the server returns.
In response to your comments:
Check what the content of the returned HTML page is. It's probably an error caused by your server-side code (e.g. an unhandled exception) or the server-side configuration.
Change this
var dataObj = {
"username": user,
"password": pass,
};
To this
var dataObj = {
"username": user,
"password": pass
};
You have an extra comma , ("password": pass,) after pass, so it is not able to serialize it properly.
Edit:
Try this
[WebMethod]
public static string login()
{
//bool UserIsValid = false;
//string userName = "";
//string pass = "";
//MembershipUser u = Membership.GetUser(userName);
//pass = u.GetPassword();
//if (UserIsValid)
//{
// // returnAsHtml = "true";
//}
//else
//{
// //returnAsHtml = "use is not valid";
//}
//JavaScriptSerializer js = new JavaScriptSerializer();
//string result = js.Serialize("{ a:'1' }"); // no need to serialize
return "{ a:'1' }";
}
so sorry!!!
in other section a called this
$('#button-login').live('click', function () {
$.ajax({
url: 'Checkout.aspx?login',
type: 'post',
data: $('#checkout #login :input'),
dataType: 'json',
beforeSend: function () {
$('#button-login').attr('disabled', true);
$('#button-login').after('<span class="wait"> <img src="Resource/Images/loading.gif" alt="" /></span>');
},
complete: function () {
$('#button-login').attr('disabled', false);
$('.wait').remove();
},
success: function (json) {
$('.warning, .error').remove();
if (json['redirect']) {
location = json['redirect'];
} else if (json['error']) {
$('#checkout .checkout-content').prepend('<div class="warning" style="display: none;">' + json['error']['warning'] + '</div>');
$('.warning').fadeIn('slow');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});