Reputation: 5242
I have a JS function:
$(document).on('click', '#submitForm', function (e) {
var fileName = $('#fileName').val();
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'bool',
success: function (result) {
if (result.returnvalue) {
e.preventDefault();
alert(result.returnvalue);
alert("The filename already exists. Please choose another one");
}
else {
alert("The file doesn't exist");
}
}
});
});
My action:
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 });
}
What am I doing wrong here? I'm trying to get the bool value from FileExist method, and if it's true stop the form from submitting (e.preventDefault)
Upvotes: 0
Views: 3117
Reputation: 44550
First, specify dataType: 'json'
in your jquery ajax request:
$.ajax({
// <...>
dataType: 'json'
// <...>
});
If you would like to use HTTP GET
:
public ActionResult FileExist(string fileName)
{
// <...>
return Json(model, JsonRequestBehavior.AllowGet);
}
You can use HTTP POST
method:
[HttpPost] // Add this attribute.
public ActionResult FileExist(string fileName)
{
// <...>
return Json(model);
}
Upvotes: 1
Reputation: 18566
The available data types in a service call are:
- xml
- html
- script
- json
- jsonp
As per your code:
change the dataType to json as you are returning json from the server.
And by default the ActionResult will be using GET
while in your ajax call you have specified POST
.
So include [HttpPost]
at the top of the method.
Upvotes: 0
Reputation: 2355
Add [HttpPost]
to your controller,set dataType:'json' and set async:false
in jquery ajax why do you need POST method. Just use GET method and add JsonRequestBehavior.AllowGet
in your controller
Upvotes: 1
Reputation: 62488
put datatype
asjson
not bool ans also add [HttpPost]
attribute on your action or other way is to put type:'GET'
Upvotes: 0
Reputation: 165
On top of your controller method, you have to put this annotation:
[HttpPost]
Upvotes: 1
Reputation: 22619
There is no dataType: 'bool'
. Please use dataType:'json'
dataType:'text'
to send the boolean values
In your case, it should be dataType:'json'
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'json',
success: function (result) {
if (result.returnvalue) {
e.preventDefault();
alert(result.returnvalue);
alert("The filename already exists. Please choose another one");
}
else {
alert("The file doesn't exist");
}
}
});
Then
[HttpPost]
public ActionResult FileExist(string fileName)
{
}
Upvotes: 2