Dynatree ASP.NET MVC: post tree to server - javascript

I want to post data from dynatree to my asp.net mvc server via ajax. I use the model classes (Dynatree with ASP.NET MVC) from Steve which work well for getting data from the server to the client. But i have still problems with posting the tree data to the server.
Client:
var td = $("#tree").dynatree("getTree").toDict();
var json = JSON.stringify(td);
$.ajax({
type: "POST",
url: "/parttree",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
}
});
Server:
[POST("/parttree")]
public ActionResult TreeData2( List<TreeItem> ot)
{
// ot is always null here
}
Content of json in VS debugger:
{"title":null,"key":"_1","isFolder":false,"isLazy":true,"tooltip":null,"href":null,"icon":null,"addClass":null,"noLink":false,"activate":false,"focus":false,"expand":true,"select":false,"hideCheckbox":false,"unselectable":false,"children":[{"title":"root","key":"_2","isFolder":false,"isLazy":false,"tooltip":null,"href":null,"icon":null,"addClass":null,"noLink":false,"activate":false,"focus":false,"expand":false,"select":false,"hideCheckbox":false,"unselectable":false,"children":....

I would say that it would be the following :
$.ajax({
type: "POST",
url: "/parttree",
data: {tree: json},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
}
});
And your MVC Action would be :
[HttpPost]
public ActionResult PartTree(FormCollection form)
{
List<TreeItem> ot = new JavaScriptSerializer().Deserialize<List<TreeItem>>(form["tree"]);
}
Although you are probably looking to a JsonResult not an ActionResult if you are returning JSON.

Related

Cannot send data from aspx file to code behind using $.ajax({ type: "POST", using VS2017 C#

I'm using web-forms to collect data from a form and then send the data to the code-behind to send to an API. Using a button I'm calling a JavaScript method which collates the data and then sends to my aspx.cs file to send to the API. The Html code for the button is
<button class="search btn" ID="btnSearch" onclick="searchApi(); return false;"><i class="fas fa-search"></i>Search</button>
This runs the searchAPI() function which works and creates a concatenated string called SearchData. The Javascript code looks like this
var searchString = JsonData;
var trimsearchString = searchString.replace(/,/g, '');
$.ajax({
type: "POST",
url: 'Default.aspx/GetApi',
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (errordata) {
console.log(errordata);
alert(errordata);
}
});
The method GetAPI in my Default.aspx.cs file is never called. The method code is
[System.Web.Services.WebMethod]
public static void GetApi(string searchData)
{...
The success: function (data) returns success but the code behind method is never called, can someone please tell me what I am missing.
fix the ajax data, it seems that method with this parameter can' t be found
$.ajax({
type: "POST",
url: 'Default.aspx/GetApi',
data: { searchData: trimsearchString},
//or if it is still problem, you can even try
data: JSON.stringify( { searchData: trimsearchString}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (errordata) {
console.log(errordata);
alert(errordata);
}
});
and your webmethod should return something
[WebMethod]
public static string GetApi(string searchData)
{
return searchData
}

ASP.NET Core Razor Pages Download File from AJAX Post

Hello I am having issues downloading a file from an ASP.NET Core Razor page using an AJAX Post. What I want to do seems repetitively simple but has proved to be a real pain.
I do not want to store the file on the server but I am alright with TempData and a guid if needed.
I want to do a ajax post because I am sending data from the client to build the file.
Data sent to server will be encrypted into a string and that will be the contents of the file. (Note: Encryption is already working)
I want the file to download as my own extension *.dat.
Here is my asp.net core razor post method.
public IActionResult OnPostDownloadEncryptedFile([FromBody] List<FileData> fileData)
{
var response = ...THIS IS A REST WEB API CALL ASYNC I am calling .Result
var byteArray = Encoding.ASCII.GetBytes(response.EncryptedData);
var stream = new MemoryStream(byteArray);
return this.File(stream, System.Net.Mime.MediaTypeNames.Application.Octet, "myfile.dat");
}
Here is my Ajax post code:
$.ajax({
type: "POST",
url: "/MySite/MyPage?handler=DownloadEncryptedFile",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(myData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (response) {
alert(response);
}
});
I realize that the ajax post is most likely incomplete and wrong not quite sure how to fix I have seen others using window.location but I am not sure how that works. Since when debugging I never have been able to get into the ajax post success function.
Any help would be greatly appreciated.
I got it working but I feel like its a terrible implementation.
Here is what I did:
public IActionResult OnPostEncryptFileData([FromBody] List<FileDataItem> fileData)
{
var response = this.restEndpoint.EncryptFileData(
new FileDataEncryptionRequest()
{
FileDataListItems = new FileDataList() { FileDataItems = fileData.ToList() }
}).Result;
return new JsonResult(response.EncryptedData);
}
public FileResult OnGetDownloadEncryptedFile(string data)
{
var byteArray = Encoding.ASCII.GetBytes(data);
return this.File(byteArray, "text/plain", "test.dat");
}
The Ajax post:
$.ajax({
type: "POST",
url: "/MySite/MyPage?handler=EncryptFileData",
beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val()); },
data: JSON.stringify(fileData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
window.location = "/MySite/MyPage?handler=DownloadEncryptedFile&data=" + response;
},
failure: function (response) {
alert(response);
}
});
Would love to hear some better solutions.

Submitting Ajax request from external javascript file in ASP.NET MVC

I am trying to submit an ajax request from an external JavaScript file in ASP.NET MVC. I'm getting a 500. What am I doing wrong?
Ajax call (From external JS file)
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Controller Action Method (That should be catching the request)
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpGet]
public void AjaxEndpoint()
{
var thing = 1 + 2;
}
// AJAX endpoint for GetProducts.js
[HttpPost]
public void AjaxEndpoint(string jsonData)
{
var thing = 1 + 2;
}
}
Error I'm getting
You either need to remove the contentType option
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
dataType: "json",
success: successFunc,
error: errorFunc
});
or alternatively, stringify the data
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: JSON.stringify({ jsonData: "testing" }),// modify
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Your ajax call needs to be to an ActionResult in the controller, The controller performs and returns the data to the page
[HttpPost]
public ActionResult ajaxcall(string ids)
{
String Data = code to perform
return Json(Data);
}
this is the basic idea. Javascript makes the call and uses the json data returned on the clients page

How can I send files along with other field's data to webmethod is asp.net using jquery ajax call?

I have a webform which has x number of textboxes and y number of dropdowns etc
I am using this code to send data to webmethod at the server:
$.ajax({
type: "POST",
url: "SupplierMaster.aspx/RegisterSupplier",
data: JSON.stringify({
id: $('#txtbidderid').val(),
bidamt: $('#txtbidamt').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
Now the problem is that I also want to include file attachments on this form.
How do I add the files to data: of $.ajax method?
I do not want to use external plugins etc unless absolutely necessary.
Lets say I modify my data object to look like this :
var dataToSend = {};
dataToSend.id = $('#txtbidderid').val()
dataToSend.bidamt = $('#txtbidamt').val()
dataToSend.append( 'file', input.files[0] );
What would the webmethod armument look like?
For example lets suppose it looks like this as of now:
[WebMethod] public static string SubmitBid(string id, string bidamt.....)
You can try something like this. You may need to manipulate content type.
var dataToSend = new FormData();
dataToSend.append( 'file', input.files[0] );
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
data: dataToSend,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
You cannot send file as application/json; charset=utf-8 to the server and so i suggest you to use application/x-www-form-urlencoded as contentType and also data as FormData as below.
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
type: 'POST',
data: new FormData(formElement),//Give your form element here
contentType: false,
processData: false,
success: function () {
//do success
}
});

How to call this.Page (server page) from javascript

I have methos to display content of page at server side like
DisplayDetails(Page PageNema)
{
///
}
How can i call this function from javascript as well as how can i pass Page argument from Javascript
If it's WebForm you must set this method as WebMethod, so then you can call this method from jQuery. Something like that:
Client Side.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Server side:
public partial class _Default : Page
{
[WebMethod]
public static string DisplayDetails()
{
//your code to retrieve details here
return Details;
}
}
[WebMethod]
public static string DisplayDetails(parameter1,parameter2,etc...)
{
return something;
}
Client side code
<script type="text/javascript">
function functionName(callback) {
$.ajax({
type: "POST",
url: 'PageName.aspx/DisplayDetails',// your function name
data: '{"argument1","argument2",etc...}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// If u want something from serverside function then write your code here
},
error: function (e) {
}
});
}
</script >

Categories