Can't find controller method when deployed - c#

Controller:
[HttpPost]
public ActionResult FileExist(string fileName)
{
bool result = true;
string path = Server.MapPath(TempPath) + fileName + ".xlsx"; //Path for the file
string[] Files = Directory.GetFiles(Server.MapPath(TempPath));
for (int i = 0; i < Files.Length; i++)
{
if (path == Files[i])
{
//The filename already exists
result = false;
}
}
return Json(new { returnvalue = result });
}
My JS:
$(document).on('click', '#saveButton', function () {
var fileName = $('#fileName').val();
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
if (!result.returnvalue) {
$('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
$('#downloadButton').css("visibility", "hidden");
}
}
});
});
When I debug this in VS it works fine. But when I have Published and put it up on a server it wont work.
My error looks like this:
Why is this not working when published?

Considering that Calculation is your Controller Class, try to give the ajax request as following
$.ajax({
type: 'POST',
url: '#Url.Action("FileExist","Calculation")',,
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
if (!result.returnvalue) {
$('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
$('#downloadButton').css("visibility", "hidden");
}
}
});
And if this event is written in a seperate js file then here is a code for that.
In your View make a js function as
function GetUrlToCheckIfFileExist(){
return '#Url.Action("FileExist","Calculation")';
}
And in your js file use the following code
var getUrlToCheckIfFileExist = window.GetUrlToCheckIfFileExist();
$.ajax({
type: 'POST',
url: getUrlToCheckIfFileExist,
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
if (!result.returnvalue) {
$('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
$('#downloadButton').css("visibility", "hidden");
}
}
});

Make the url in view and set in a javascript variable and use it in your js file.
for cshtml file
<script>
var urlpath = '#Url.Action("FileExist","Calculation")';
</script>
for js file
$(document).on('click', '#saveButton', function () {
var fileName = $('#fileName').val();
$.ajax({
type: 'POST',
url: urlpath,
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
if (!result.returnvalue) {
$('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
$('#downloadButton').css("visibility", "hidden");
}
}
});
});

Related

Ajax not hitting controller method

I have the following jquery function which is sending data to a controller:
function bound(e) {
var ele = document.getElementsByClassName("e-grid")[0]
ele.addEventListener('click', function (e) {
if (e.target.classList.contains('e-up')) {
var grid = document.getElementById('FlatGrid').ej2_instances[0]; //Grid Instance
var rowObj = grid.getRowObjectFromUID(ej.base.closest(e.target, '.e-row').getAttribute('data-uid'));
var data = rowObj.data;
//alert(JSON.stringify(data));
var code = data.ClientCode;
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { "ClientCode": code }, //First item has latest ID
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
}
});
}
And my controller method:
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
*action*
}
However I am getting a 500 (Internal Server Error) error for this. Any idea what I am missing cause my method is not being hit at all.
And I can see that var code does have the correct string value.
Remove commas from the parameter name "ClientCode" and contentType and will be work
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { ClientCode: code }, //First item has latest ID
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
The comments have provided you with a combination of suggestions that when put together will give you the desired behavior.
First, you can build the URL in teh view using #Url.Action
url: '#(Url.Action("ShowClient","Client"))',
Next, the object model is not being built correctly
data: { ClientCode: code },
Note the last of quotes around the key.
And finally remove the JSON content type.
Which results to portion of code.
$.ajax({
type: "POST",
url: '#(Url.Action("ShowClient","Client"))',
data: { ClientCode: code },
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
Change the url to this:
url: "../Client/ShowClient"

Send file with ajax of jQuery to web service in C# (asmx)

I'm using web service with this method:
$.ajax({
type: 'POST',
url: 'page.asmx/method',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{}'
});
Sending json string, and it works, but if I try to append with FormData the content of input and passing it in data value I have 500 response. What have I to do?
You need to serialize you data....
var data = new FormData();
var files = $("#YOURUPLOADCTRLID").get(0).files;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
// Make Ajax request with the contentType = false, and procesDate = false
var ajaxRequest = $.ajax({
type: "POST",
url: "/api/fileupload/uploadfile",
contentType: false,
processData: false,
data: data
});
And inside the controller you can have something like
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
Hope it helps...
You can send form object like : new FormData($(this)[0]) which send both input values and file object to the ajax call.
var formData = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: 'page.asmx/method',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
Send Client side value server side through jquery and ajax call.
Click On butto send value client side to server side
<script>
$(document).ready(function () {
$("#additembtn").click(function () {
jQuery.ajax({
url: '/TelePhone/Edit',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {
Name: $('#txtUsername').val(),
Address: $('#txtAddress').val(),
},
error: function (request, status, error) {
},
sucess: function (data, status, request) {
}
})
});
});
</script>
// Web Servics Telephone.asmx
[HttpPost]
public ActionResult Edit(string data)
{
}

The simplest way to download file with existing path from jquery?

I went through dozen of pages with question "How to download file from jQuery", but still didn't find the simple solution.
I have my jQuery with ajax inside:
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: JSON.stringify({ 'Matters': result, 'originalRecords': originalRecords, 'originalHours': originalHours, 'excludedHours': excludedHours, 'totalHours': totalHours }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
var DownloadableFile = data.message;
//HERE I NEED TO DOWNLOAD FILE
alert("Success! You will be redirect to the Home Page.");
var url = '#Url.Action("Index", "Home")';
window.location.href = url;
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
Here in data.message I'm getting back from Action SaveQBMatter FULL FILE PATH
What I need is simply let to my user download this file before redirecting. Any help please?
Note: I'm using ASP.NET MVC, if this information is needed
Try to use this plugin for downloading the file:
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
You can do something like this, upon a successful ajax call, do location.href = data.message; which as you said data.message is the full path to the file. With that, it should download the file without redirecting the browser. Also when you download the file, make sure you have the header force-download.
You can see more about forcing a download here:
http://www.symkat.com/force-download-with-http-headers
Then, do a setTimeout of lets say 1 to 2 seconds, you can tweak the timings to how you like it, to let the download initialize and redirect. So your code would look like this:
$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: JSON.stringify({ 'Matters': result, 'originalRecords': originalRecords, 'originalHours': originalHours, 'excludedHours': excludedHours, 'totalHours': totalHours }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
var DownloadableFile = data.message;
location.href = DownloadableFile;
setTimeout(function() {
alert("Success! You will be redirect to the Home Page.");
var url = '#Url.Action("Index", "Home")';
window.location.href = url;
}, 1000);
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
Try opening the URL in a new window, if not blocked by the users browser:
if (data.status == "Success") {
window.open(data.message, "_blank")
If you have problems with the file opening instead of downloading, you can try sending a content disposition header from ASP like:
Content-Disposition: attachment; filename="filename.extension"

How to pass multipart/form-data to c# method via Ajax

I am using html2canvs.js for taking screen shots of the page which is described here:
How to take screen shot of current webpage using javascript/jquery
The above process works fine, but now I want to pass the Base64 data to a c# method via ajax. My code looks like:
$('#gbox_Basic').html2canvas({
onrendered: function (canvas) {
var imgString = canvas.toDataURL("image/png");
$.ajax({
type: "POST",
url: "/Home/SentEmail2",
data: //how to pass base64 data 'imgString' ,
contentType: "multipart/form-data",
success: function () {
}
});
}
});
And here is my c# method
public void SentEmail2(what type of param it would accept?) {
//process incoming params
}
Give a try to this:
Controller.cs
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
Form
The object FormData will hold the file element to be send.
var formData = new FormData($('form')[0]);
$.ajax({
url: '/Home/SentEmail2', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
References:
http://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3
http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/

JSON TinyMCE return value "\t"

Should I use another variable for "streszczenie"? or what should I do?
In my opinion in TinyMCE body have html but I get only "\t" Pobably I have got problem with JS
this is new problem - this question is related with this link. I added this for other users
this I write in TinyMCE
this I get from TinyMCE textarea "streszczenie"
As you can see there is text ghhfgh but I can`t get this text
Now I have got problem with execute JSON
<script type="text/javascript">
function Save() {
tinyMCE.triggerSave();
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function() {
},
success: function(data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
I get this but all the time JSON is not execute
When I click button tinyMCE.get('Streszczenie').getContent() is empty I check this and I don`t know why because I have got text into textarea
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var $d = tinyMCE.get('Streszczenie').getContent();
if ($d.length != 0) {
if ($d.val().length != 0) {
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
}
else {
var Streszczenie_controll = 'ewewe';
}
}
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
You are getting the content in wrong way, not by jQuery's val().
To get the tinymce content, just use tinyMCE object reference:
// Get the HTML contents of the currently active editor
console.debug(tinyMCE.activeEditor.getContent());
// Get the raw contents of the currently active editor
tinyMCE.activeEditor.getContent({format : 'raw'});
// Get content of a specific editor:
tinyMCE.get('content id').getContent()
As mentioned:
http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.getContent
Hope it heled. Polish man : )

Categories