How can I pass parameter to .NET web method with fancytree
Public Shared Function ReadNodes(parentId As String) As String
I am trying to send it like this, but it always gets sent as a querystring parameter.
$("#tree").fancytree( {
source: {
url: "Default.aspx/ReadNodes",
data: {parentId: "-1"},
cache: false
}
} )
Can I somehow pass the value to a method as a parameter?
This doesnt work, I keep getting a loading wheel and then a failure. No javascript errors in console.
I have also tried the server method without a parameter, and I get the same behavior. So perhaps I am doing something else wrong.
Your web method must return an array like:
[WebMethod]
public static IEnumerable ReadNodes(int parentId)
{
return new[] {
new { title = string.Format("1. Child of '{0}'", parentId) },
new { title = string.Format("2. Child of '{0}'", parentId) }
// ...
};
}
And then you call the web method like this
$('#tree').fancytree({
source: {
type: 'POST',
url: 'Default.aspx/ReadNodes',
data: '{ parentId: -1 }',
contentType: 'application/json;',
dataType: 'json'
}
});
Related
I need to implement functionality to upload files and save them relevant to the orderItemID (which I can get). The problem isn't getting the ID or using the ID to then save the files to the DB. The problem is passing this ID (which I can log out and see is there) into the controller to then be used, the parameter continues to come back NULL when it isn't.
I initially tried passing the orderItemID as a second parameter when uploading the document but that resulted in both the HttpPostedFileBase and the int of orderItemID coming back as NULL as soon as I entered the method.
I've tried passing the orderItemID through the ViewBag. feature but again it comes back as NULL
I'm now trying to make a second separate AJAX call which simply passes in an int (orderItemID) and then in the controller I can try other things but for now I'd just like to see the parameter not returning as NULL when I hit the breakpoint in the orderController.
View:
$('#confirmUploadDiagrambtn').on("click", function () {
var currentID = document.getElementsByName("orderitemid")[0].value;
var form = $("#file")[0].files[0];
var datastring = new FormData();
datastring.append('file', form);
//Order Item ID is logged out as the expected 12121
console.log("OrderID: " + currentID);
//Errors out saying parameter is NULL
setOrderItemID(currentID);
uploadDocument(datastring);
})
function setOrderItemID(cOrderItemID) {
$.ajax({
type: "POST",
url: '/Order/SetCurrentOrderItemID',
data: cOrderItemID,
contentType: false,
processData: false,
success: function (response) {
console.log('Item Success');
console.log(response);
},
error: function (status) {
console.log('Item Error');
console.log(status);
}
})
}
Controller:
[HttpPost]
public void SetCurrentOrderItemID(int orderItemID)
{
//I can try whatever later, just need the param to not be NULL
ViewBag.cOrderItemID = orderItemID;
}
Expected: orderItemID will equal 12121
Actual: NULL
Error: The parameters dictionary contains a null entry for parameter 'orderItemID' of non-nullable type 'System.Int32' for method 'Void SetCurrentOrderItemID(Int32)'
the "data" property in the AJAX parameters should look like:
data: "cOrderItemID=" + cOrderItemID
EDIT:
remove this line:
contentType: false,
use this format:
data : {OrderItemID : cOrderItemID}
By default int parameters are assumed to come from the query string, you could either change the url to:
function setOrderItemID(cOrderItemID) {
$.ajax({
type: "POST",
url: '/Order/SetCurrentOrderItemID?orderItemID=' + cOrderItemID,
contentType: false,
processData: false,
success: function (response) {
console.log('Item Success');
console.log(response);
},
error: function (status) {
console.log('Item Error');
console.log(status);
}
})
}
Or else you could mark the parameter with the [FromBody] attribute:
[HttpPost]
public void SetCurrentOrderItemID([FromBody] int orderItemID)
{
//I can try whatever later, just need the param to not be NULL
ViewBag.cOrderItemID = orderItemID;
}
and then update your data parameter to:
data: JSON.stringify({orderItemId: cOrderItemID}),
I am trying to post values from MVC view to controller.
Request validation feature is enabled for application.
But when i tried to pass values with HTML tags to controller, I am not getting any exception.
here is my ajax post:
Group.Name = model.Name();
Group.Id = model.ID();
$.ajax({
type: 'POST',
url: /IndexController/SaveGroup',
async: true,
cache: false,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Group: group }),
success: function (data /*, textStatus, request*/) {
try {
}
catch (error) {
showExceptionWindow('Jquery Error:' + error);
}
},
error: function (request /*, status, error*/) {
handleException(request.responseText);
}
});
}
Controller Code:
[HttpPost]
public async Task<ActionResult> SaveGroup(Group group)
{
when i tried to insert html tags,the values are passing to controller action method and getting saved.
When request validation feature is enabled,html elements should not be passed to controller.
How to make sure it is getting blocked at controller.
MVC validation dosent work since you've changed the submit button to prevent default mvc use the jquery plugin Validate.js just go through i,this code should work
var form = $("#YourFormID");
form.validate();
form.submit(function (e) {
e.preventDefault();
if (form.valid()) {
//Your ajax call
}
})
Seems you have a typo as there group does not seem to be a valid object it is undefined:
data: JSON.stringify({ group: Group }), // <-----It should have to be this Group here
And at your backend:
[HttpPost]
public async Task<ActionResult> SaveGroup(Group group) // group is {}
{
Or as Group is already an object then you can stringify it directly:
data: JSON.stringify(Group), // <-----It should have to be this Group here
[HttpPost]
public async Task<ActionResult> SaveGroup(Group Group) // group is {}
{
Why not using an HTML parser to detect HTML elements injection? This can be a clean JS solution
var containsHTML = /<[a-z][\s\S]*>/i.test("<p>HTML text to be parsed</p>")
if(containsHTML==true){
//There are HTML tags inside the string
}
else{
//You're good to go
}
I'm trying to pass a string parameter to a javascript function from the server side which will be posted to an AJAX method. The html is dynamically generated at the server side and I'm calling the javascript function using onclick property. The problem is that it works for a numeric value but I get an internal server error when I pass in a string value.
here's my server side code:
str.Append("<span class=\"button-accept\"><a class=\"btn btn-primary btn-sm\" onclick=\"Request('"+from.ToString()+"')\" href=\"#\"><i class=\"fa fa-check\"></i></a></span>");
Here's my javascript method:
function Request(param) {
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/myaccount/notifications/Default.aspx/Accept") %>',
data: "{'param' : "+param+"}",
contentType: "application/json",
success: function (msg) {
msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
and here's the method that will be called by AJAX:
[WebMethod]
public static string Accept(string param)
{
return param;
}
What's the right way to do this?
The JSON you are passing to the web method is implying that it is an numeric value, add quotes surrounding the param value:
Old
data: "{'param' : "+param+"}",
New
data: "{'param' : '"+param+"'}",
Alternatively ...
If a string is always passed to your Request method, it will be correctly handled using JSON.stringify
data: JSON.stringify({ 'param' : param }),
I am feeling dejavu, but I cannot find the answer to this:
I have an array of objects that needs to look like this when inspecting a jQ $.post call:
limiter[0].Key
limiter[0].Value
so that it is mapped in the action
public ActionResult SomeAction(Dictionary<Guid, string> dictionary) { }
However, this javascript:
// Some Guid and Some Value
var param = [ { 'Key' : '00000000-0000-00000-000000', 'Value': 'someValue' } ];
$.post('/SomeController/SomeAction/',
{
dictionary: limiter,
otherPostData: data
},
function(data) {
callback(data);
}
)
produces this when inspecting it in firebug:
limiter[0][Key] = someKey // Guid Value
limiter[0][Value] = someValue
This is in jq 1.4.2. I seem to remember some flag you need to set to render json a different way in jQ. Does this ring any bells?
Try like this:
var param = {
'[0].Key': '28fff84a-76ad-4bf6-bc6d-aea4a30869b1',
'[0].Value': 'someValue 1',
'[1].Key': 'd29fdac3-5879-439d-80a8-10fe4bb97b18',
'[1].Value': 'someValue 2',
'otherPostData': 'some other data'
};
$.ajax({
url: '/Home/SomeAction/',
type: 'POST',
data: param,
success: function (data) {
alert(data);
}
});
should map to the following controller action:
public ActionResult SomeAction(Dictionary<Guid, string> dictionary, string otherPostData)
{
...
}
var dict = {}
dict["key1"] = 1
dict["key2"] = 2
dict["key3"] = 3
$.ajax({
type: "POST",
url: "/File/Import",
data: dict,
dataType: "json"
});
public void Import(Dictionary<string, int?> dict)
{
}
just send your obj as dataType: "json"
You can use this flag -
jQuery.ajaxSetting.traditional = true;
To get jQuery to post the data in a different format to the one you are seeing. See this question for further info -
Passing arrays in ajax call using jQuery 1.4
You will see the post param as limiter[0][Key] because jquery serializes the json data before it posts it. This is very well interpreted by the controller action and you get the required input in the action.
You can also use a list of objects and the result will be the same as what you wanted. This is a nice example.
http://www.mikesdotnetting.com/Article/96/Handling-JSON-Arrays-returned-from-ASP.NET-Web-Services-with-jQuery
I'm using the following script to post to and endpoint, it's hitting the breakpoint on the server so I know the routing is correct.
$(document).ready(function() {
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(o),
dataType: 'json',
url: 'home/PingBack',
success: function(result) {
alert(result.success);
}
});
});
The endpoint on the server looks like this.
public JsonResult PingBack(MHolder message)
{
return Json(new { success = "steve"});
}
and the Model looks like this.
public class MHolder
{
public string message { get; set; }
}
I'm sure that in the past the values have been automatically bound to the model, but I can't seem to get anything to be bound atm! Even if I just pass the value as a string, I'm sure it's something silly that I'm missing any ideas?
A few things to notice. You are sending the request as a JSON string (contentType: 'application/json' and JSON.stringify(o)) while on the server you are expecting an object of type MHolder. The default model binder won't do this transformation. You will need to either write a custom model binder capable of deserializing JSON back to an MHolder instance or send the request as key=value pairs (do not stringify):
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
data: o,
dataType: 'json',
url: 'home/PingBack',
success: function (result) {
alert(result.success);
}
});
The code seems OK to me, at first glance.
try using...
data : {message : "Hi from the page."},
...to see if this causes the MHolder instance to be populated.
Also, use something like Fiddler to capture your requests and allow you to see exactly what is being posted.