I want to send data though Ajax to a C# file, but when I check the received data, It gives me null. Is there someting wrong with my code?
Javascript file
$(".save").click(function () {
var ss = "Helloo!";
$.ajax({
type: "POST",
url: "/Notes/save.cshtml",
global: true,
data: {fofo: ss},
processData: false,
contentType: false,
cache: false,
success: function(data){
console.log(data);
},
error: function (req, status, error) {
alert("There was a problem with the server. Try refreshing the page.");
return false;
}
});
});
C# File which receives the data (save.cshtml)
@{
var s = Request.Form["fofo"];
var result = "";
var userData = s;
var dataFile = Server.MapPath("~/Notes/lolo.txt");
File.WriteAllText(@dataFile, s);
result = "Information saved.";
}
@if(result != ""){
<p>Result: @result, @s</p>
}
You are not sending a response
back to your AJAX
function. Not only that what you're doing isn't standard MVC
. You should be hitting a Controller
which saves the data in the file at the server side and then send the result back using a JsonResult
.
For example:
public JsonResult SaveNotes()
{
// Code to save file here
// Return the response
return Json({NotesSaved = true});
}
Then in your JavaScript AJAX
success object you will then have the NotesSaved
object set to true.
Note: You should also change your URL
parameter in the AJAX
command to something like:
url: '@Url.Action("SaveNotes")'