MVC Ajax function call twice - ajax

I have a problem with an ajax function. I want to send param to method on controller and this ajax function call method twice.
ajax:
$(document).ready(function () {
$(document).on('click', '.exp', function (e) {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
})

$(".exp").click(function() {
var st_date = $(this).parent().find('.start').val();
var ed_date = $(this).parent().find('.end').val();
$.ajax({
url: '/Reports/Report_CLeav/',
data: {
start_date:st_date,
end_date:ed_date
}
}).success(function (data) {
})
});
?

<th>
Start date: #Html.TextBox("start_date", null, new { #class = "dateClass start", id = "StartDate" })
End date: #Html.TextBox("end_date", null, new { #class = "dateClass end", id = "EndDate", #data_toggle = "popover", #data_content = "End date should be greater than Start date. ", #title = "Attention" })
#Html.ActionLink("Export Report", "Report_CLeav", "Reports", new { #class = "IndexButton exp", #style = "text-decoration: none;color:white" })
</th>
"Controller"
public class ReportsController : Controller
{
// GET: Export
public ActionResult Index()
{
return View();
}
public void Report_CLeav(DateTime ?start_date, DateTime ? end_date)
{
string path = HttpContext.Server.MapPath("~/App_Data/reports/Report_LeavingCompanyHCT.xlsx");
Models.Report.Report_CompLeav reportcompleav = new Models.Report.Report_CompLeav();
var fileinfo = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(fileinfo))
{
var currentWorksheet = package.Workbook.Worksheets["HC"];
using (var excelToExport = new ExcelPackage())
{
excelToExport.Workbook.Worksheets.Add(currentWorksheet.Name, currentWorksheet);
var workBook = excelToExport.Workbook.Worksheets["HC"];
try
{
workBook = reportcompleav.exportAllEmployeeDataRRecords(workBook,start_date,end_date);
}
catch (Exception e)
{
ViewBag.IsError = true;
}
excelToExport.Save();
Stream stream = excelToExport.Stream;
var memoryStream = stream as MemoryStream;
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats";
Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileinfo.Name);
Response.BinaryWrite(memoryStream.ToArray());
}
}
}
}
}

Related

Getting Status 400 error while posting data on server in Razor page and AJAX

I am developing a website related to medical treatment, in which we ask different type of questions from patient actually, my task is, to enter their Email so I can check if he is already registered or not logged in then I redirect the user to the login page else I can register the user and assign a random password to the user and send him a mail on that Email,
so logged in user and if a user is not logged in these flows are working fine but when I'm when I register the user then and come to the next question I'm getting an error of status 400
Code for checking for user:
public async Task<IActionResult> OnGetCheckUserAsync(string Email)
{
if (User.Identity.IsAuthenticated)
{
var UserCred = _userManagmentServices.GetProfileAsync(Email).Result;
ProfileModel = new ProfileModel()
{
Id = UserCred.Id,
Email = UserCred.Email,
Name = UserCred.Name,
Applications = UserCred.Applications,
Address = UserCred.Address,
City = UserCred.City,
DisplayName = UserCred.DisplayName,
Phone = UserCred.Phone,
PostalCode = UserCred.PostalCode,
};
return new JsonResult(ProfileModel);
}
else
{
var user = await _userManager.FindByEmailAsync(Email);
if (user == null)
{
string randomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!##$%^&*";
Random random = new Random();
char[] myPassword = new char[6];
for (int i = 0; i < 6; i++)
{
myPassword[i] = randomString[(int)(35 * random.NextDouble())];
}
var randomPassword = string.Concat(myPassword);
var UserModel = new UserModel()
{
Email = Email,
FirstName = "Mr",
LastName = "Patient",
Password = randomPassword,
PhoneNo = "03000000000",
};
var response = await _userManagmentServices.CreateAsync(UserModel);
if (response.IsSuccessful)
{
var Body = $"Dear {UserModel.FirstName + UserModel.LastName} Your password is auto generated successfull and your password is {UserModel.Password}";
await _mailServices.SendEmailNotificationAsync(UserModel.Email, "Auto Generated Password", Body);
}
if (!response.IsSuccessful)
{
foreach (var Error in response.Errors)
{
ModelState.AddModelError("", Error.ToString());
}
return new JsonResult("Error while creating your account");
}
var UserCred = _userManagmentServices.GetProfileAsync(UserModel.Email).Result;
ProfileModel = new ProfileModel()
{
Id = UserCred.Id,
Email = UserCred.Email,
Name = UserCred.Name,
Applications = UserCred.Applications,
Address = UserCred.Address,
City = UserCred.City,
DisplayName = UserCred.DisplayName,
Phone = UserCred.Phone,
PostalCode = UserCred.PostalCode,
};
return new JsonResult(ProfileModel);
}
else
{
application = new FEApplication();
application.Status = Status.Incomplete;
application.UserEmail = Email;
application.ApplicationType = "Premature Ejaculation";
application.FlowId = await _applicationManagementService.Create(application);
var _signinUrl = "../Auth/Signin";
return new JsonResult(_signinUrl);
}
}
}
public async Task<IActionResult> OnPostSubmitAsync(FEApplication? application)
{
if (application.FlowId != null)
{
application.ApplicationType = "Premature Ejaculation";
if (application.DoctorToKnow == "No" || application.ExplainDoctorToKnow != null)
{
application.Status = Status.PaymentDue;
}
else
{
application.Status = Status.Incomplete;
}
await _applicationManagementService.UpdatePEAsync(application.FlowId, application);
}
else
{
if (User.Identity.IsAuthenticated)
{
application.PatientUserName = ProfileModel.DisplayName;
application.ApplicationType = "Premature Ejaculation";
application.Status = Status.Incomplete;
application.UserEmail = User?.Identity?.Name;
ProfileModel = _userManagmentServices.GetProfileAsync(application.UserEmail).Result;
}
else
{
application.PatientUserName = ProfileModel.DisplayName ?? string.Empty;
application.UserEmail = application.UserEmail;
}
application.Status = Status.Incomplete;
application.ApplicationType = "Premature Ejaculation";
application.FlowId = await _applicationManagementService.Create(application);
//_application = _applicationManagementService.GetOneById(FlowId);
}
return new JsonResult(application.FlowId);
}
function CheckUserEmail() {
$("#modalspinner").show();
var email = document.getElementById("Email").value;
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken" ]').val());
},
url: "./Start?handler=CheckUser",
type: "GET",
dataType: "json",
data: {
Email: email
},
success: function (response) {
console.log("Success block");
if (response) {
$("#modalspinner").hide();
console.log("response " + response)
if (response == "../Auth/Signin") {
window.location.href = response;
}
else {
if (response.id) {
console.log("if block =" + JSON.stringify(response));
var firstName = JSON.stringify(response.displayName) ?? "";
var lastName = JSON.stringify(response.displayName) ?? "";
var email = JSON.stringify(response.email) ?? "";
var phoneNo = JSON.stringify(response.phone);
var address = JSON.stringify(response.address) ?? "";
var city = JSON.stringify(response.city);
var postalCode = JSON.stringify(response.postalCode) ?? "";
$("#FirstName").val(firstName.replace(/\"/g, ""));
$("#LastName").val(lastName.replace(/\"/g, ""));
$("#Email").val(email.replace(/\"/g, ""));
$("#PhoneNoTextbox").val(phoneNo.replace(/\"/g, ""));
$("#CustomerShippingAddress").val(address.replace(/\"/g, ""));
$("#CustomerCity").val(city.replace(/\"/g, ""));
$("#CustomerPostalCode").val(postalCode.replace(/\"/g, ""));
console.log("response data :" + firstName, lastName, email, phoneNo, address, city, postalCode);
}
else {
$("#modalspinner").hide();
console.log("Error while creating new user" + JSON.stringify(response));
}
}
}
},
error: function (response) {
console.log("Error block =" + JSON.stringify(response));
$("#modalspinner").hide();
$('#EmailMessage').show();
setTimeout(function () { $('#EmailMessage').hide(); }, 5000);
$("#modalspinner").hide();
}
});
}
function SubmitForm() {
/*var flowId = document.getElementById("FlowId").value;*/
var data = $("#ApplicationData").serialize();
console.log("data :" + data);
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken" ]').val());
},
type: "POST",
url: "./Start?handler=Submit",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: data,
success: function (response) {
var res = JSON.stringify(response);
console.log("Application data saved!");
$("#FlowId").val(res.replace(/\"/g, ""));
}
})
}
Please check below with your code:
In the cshtml, add
#Html.AntiForgeryToken()
The Ajax request should send the anti-forgery token in request header to the server.
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
In startup, since the script sends the token in a header called XSRF-TOKEN, configure the antiforgery service to look for the XSRF-TOKEN header:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

File upload using AnguarJS

I wanted to upload image in an AJAX manner and did so with reference to this Article
What I have done:
Controller:
$scope.uploadImage = function () {
var result;
var formdata = new FormData();
var fileInput = document.getElementById('fileInput');
for (var i = 0; i < fileInput.files.length; i++) {
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Common/Image_upload?imageType=' + $scope.imageType);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
};
View:
<form id="uploader" ng-submit="uploadImage()">
<input id="fileInput" type="file">
<input type="submit" value="Upload file" />
</form>
MVC Controller:
[HttpPost]
public JsonResult Image_upload(string imageType)
{
....
success = ProductImage_insert(Image);
message = success ? "Image uploaded successfully!" : "Image was not uploaded!";
return Json(message, JsonRequestBehavior.AllowGet);
}
Requirement:
I need to catch this JSON response in the controller, how can I do it?
Thanks in advance.
You can do it in a angular way:
$scope.uploadImage = function () {
var fileInput = document.getElementById('fileInput');
var messageHeaders = { 'Content-Type': 'application/x-www-form-urlencoded' };
messageHeaders['X-File-Name'] = encodeURI(fileInput.files[0].name);
messageHeaders['X-File-Type'] = encodeURI(fileInput.files[0].type);
var fileData = fileInput.files[0];
$http({
url: '/Common/Image_upload',
method: "POST",
data: fileData,
headers: messageHeaders
}).success(function (data, status, headers, config) {
// do what you want with the response
});
}
on the server read Request.InputStream for a file content
[HttpPost]
public virtual ActionResult Image_upload(productType)
{
var xfileName = HttpUtility.UrlDecode(Request.Headers["X-File-Name"]);
var xfileType = HttpUtility.UrlDecode(Request.Headers["X-File-Type"]);
var inputStream = Request.InputStream;
var fileLenght = (int)inputStream.Length;
var bytes = new byte[fileLenght];
Request.InputStream.Read(bytes, 0, fileLenght);
System.IO.File.WriteAllBytes(Server.MapPath("/MyFiles/" + xfileName), bytes);
// return status code 200 or any other data
return new HttpStatusCodeResult(200);
}

how to fetch workerID in my kendoDropdown list

i have a kendodropdown list with the workername and details... how can i fetch the ID of the selected worker so i can able to save... everytime i save it returns a null value in ID.. thanks for those who can help
Heres my code:
<input id="titles" class:"validate[required] inputLong" style="width: 400px;" />
$(document).ready(function () {
var clientCusPosId = $("#clientCusPosId").val();
$("#titles").kendoDropDownList({
dataTextField: "workerName",
dataValueField: "workerID",
autoBind: false,
// define custom template
template:
'<h5>${ data.workerName }</h5>' +
'<p>${ data.workerID }</p>' +
'<p>${ data.AvailableDay_LookID }</p>' +
'<p>${ data.StartTime } - ${ data.EndTime }</p>',
optionLabel: "Assign worker",
dataSource: {
transport: {
read: {
url: '/Client/LoadWorkerDropdownList?clientCusPosId=' + clientCusPosId,
dataType: "json",
type: "POST"
}
}
}
});
var dropdownlist = $("#titles").data("kendoDropDownList");
dropdownlist.list.width(250);
});
My Controller:
[Authorize]
[HttpPost]
public ActionResult ClientWorkerPositionSave(FormCollection formCollection)
{
String msg = String.Empty;
String clientWorkerPosId = formCollection["clientWorkerPosId"];
String clientID = formCollection["clientId"];
String clientCusId = formCollection["clientCusPosId"];
String workerID = formCollection["titles"];
Client_Worker_Position clientCusPos = new Client_Worker_Position();
try
{
if (String.IsNullOrWhiteSpace(clientWorkerPosId) || clientWorkerPosId == "0")
{
clientCusPos.ClientCustomerPositionID = Convert.ToInt32(clientCusId);
clientCusPos.WorkerID = Convert.ToInt32(workerID);
clientCusPos.ClientID = Convert.ToInt32(clientID);
clientCusPos.DateCreated = DateTime.UtcNow;
clientCusPos.DateModified = DateTime.UtcNow;
clientCusPos.CreatedBy = User.Identity.Name;
clientCusPos.ModifiedBy = User.Identity.Name;
db.Client_Worker_Position.Add(clientCusPos);
}
else
{
int id = Convert.ToInt32(clientWorkerPosId);
clientCusPos = (from a in db.Client_Worker_Position
where a.ID == id
select a).SingleOrDefault();
clientCusPos.ClientCustomerPositionID = Convert.ToInt32(clientCusId);
clientCusPos.WorkerID = Convert.ToInt32(workerID);
clientCusPos.ClientID = Convert.ToInt32(clientID);
clientCusPos.DateModified = DateTime.UtcNow;
clientCusPos.ModifiedBy = User.Identity.Name;
}
}
catch (Exception)
{
msg = "Failed to save";
}
db.SaveChanges();
if (String.IsNullOrWhiteSpace((msg)))
{ TempData["message"] = "Saved Successfully."; }
else if (msg != "")
{ TempData["message"] = msg; }
return RedirectToAction("ClientCustomerDetails", new { });
}
It could be as simple as using $("#titles).val() to get your WorkerID since it has already been configured.
Create a hidden input field hidden id="workerID" then before your post or in a drop down change event set it to $("#workerID").val($("#titles).val()). This should come across in your controller collections.

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