I have a javascript method which contains an ajax call:
function MyFunction(urlTask, task) {
...
ajax({
url: urlTask,
data: task.Params,
type: 'POST',
dataType: 'json'
})
...
}
urlTask is the name of a method in the controller and its name varies depending on some conditions. As a example, sometimes it can be Task1 and sometimes Task2:
[HttpPost]
public ActionResult Task1(string Param1, string Param2)
{
}
[HttpPost]
public ActionResult Task2(string Param1)
{
}
Each controller method has a different number of parameters, for example, Task1 has two parameters whereas Task2 has one. So as method in the controller to be called from jquery ajax can vary as well as its parameters I use the above commented scenario, that is, passing the name of the task (urlTask) and task to the javascript function and finally, passing them through the ajax call to the method in the controller.
task.Params contains the necessary parameters to be passed to the controller for each case, either Task1 or Task2. (see below explanation).
What I want is to build the parameters to be passed to the controller method as a string, and then assign it to the 'Data' in the ajax call. task is a json object returned previously by the controller and it contains a field called Params, among others. Params field is a string type which contains the correct parameters depending on the controller method to be called. For example:
task.Params contains a string like below when calling Task1 controller method:
{'Param1':'Param_1','Param2':'Param_2'}
and:
{'Param1':'Param_1'}
when calling Task2 controller method:
My problem is: Controller method, either Task1 or Task2, is receiving its parameters as null so what's wrong? It seems like ajax call is not interpreting correctly the 'data' argument when sending it to the controller method.
Using below in the ajax call is not working:
contentType: 'application/json',
data: JSON.stringify(task.Params)
Any ideas?
contentType: 'application/json',
data: JSON.stringify(task.Params)
Worked for me.
My controller:
[Authorize]
[HttpPost]
public ActionResult Test(string Param1, string Param2) {
return Json(new{ Msg = "Param1: " + Param1 + " & Param2: " + Param2}, JsonRequestBehavior.AllowGet);
}
JS:
var Task={};
Task.Params = {'Param1':'Param_1','Param2':'Param_2'};
$.ajax({
url: "/Test",
type: "POST",
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(Task.Params),
success: function (data) {
alert(data.Msg);
}, error: function (data) {
}
});
Output is: {"Msg":"Param1: Param_1 \u0026 Param2: Param_2"}
the other way I used in my project:
in javascript:
var sData = "Param1=" + encodeURIComponent(jsParam1) + "&Param2="+ encodeURIComponent(jsParam2);
jQuery.ajax:
...
url: '{server side task1 url}',
type: 'POST',
data: sData ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
...
server side:
[HttpPost]
public ActionResult Task1(string Param1, string Param2)
{
string sUnescapedParam1 = System.Uri.UnescapeDataString(Param1);
string sUnescapedParam2 = System.Uri.UnescapeDataString(Param2);
}
You can pass the object by converting it as json object like the following syntax
function MyFunction(urlTask, task) {
$.ajax({
url: urlTask,
data: "{" + JSON.stringify(task.Params) + "}",
type: 'POST',
contentType: "application/json;charset=utf-8",
dataType: "json",
success: onSussess,
error: onError
});
}
Related
I have a simple controller method that should return a JSON result but returns null. I need to call it using jQuery $.ajax. I tested it using Postman and it does return null. I am not sure what I am doing wrong.
I tested it with Postman using the following JSON data and it returns null:
{ "id": 2 }
Here is the controller method:
// Post: Contact
[HttpPost, ActionName("GetContact")]
public JsonResult GetContactPost([FromBody] long id)
{
var contact = _context.Contact.SingleOrDefault(m => m.ContactId == id);
return Json(contact);
}
In my application I am using the following JavaScript and it returns null as well:
function GetContact(id) {
$.ajax({
type: "POST",
url: "#Url.Action("GetContact","Contacts")",
data: { id: id },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("id: " + id + " result: " + result);
},
failure: function (response) {
alert(response.d);
}
});
}
I figured it out. The parameter has to be a model or view model object.
// Post: Contact
[HttpPost, ActionName("GetContact")]
public JsonResult GetContactPost([FromBody] ContactVM findContact)
{
var contact = _context.Contact.SingleOrDefault(m => m.ContactId == findContact.Id);
return Json(contact);
}
Hi I have a drop down in View and for select index change I am using Jquery like this
$(function () {
$('#IncidentObj').change(function () {
var selectedValue = $(this).val();
alert(selectedValue)
$.ajax({
url: '#Url.Action("Index", "Operation")',
type: 'GET',
cache: false,
data: { value: selectedValue },
success: function (data) {
alert(data.success)
}
});
});
});
How can I get the value of selectedvalue into controller?
To pass the value to the Index action method within your Operation Controller you need to make sure your Index action method within your Operation Controller has a parameter named "value" like so:
public class OperationController{
public ActionResult Index(String value){
// do stuff here with "value"
...
...
}
...
...
}
where the "String" type I specified for the method parameter "value", can be changed to Int, bool, ect.. to fit your needs.
The reason why the method parameter is named "value" and not something else is because in your ajax call you specified:
data: { value: selectedValue },
I have a RESTFUL WCF services PUT method with parameters and I have not been able to execute it with the proper parameter values.
OperationContract()
WebInvoke( Method:="PUT", UriTemplate:="/Fixit/{Id}")
Public Sub UpdateLocation(ByVal Id As String, ByVal location As Location)
End Sub
Location is a class and it has theses properties:
DataContract(Name:=MyLocation,Namespace="")
Public class Location
DataMember(Order:=1)
Public Property Name As String
DataMember(Order:=2)
Public Property Address As String
End Class
I have tried using WebRequest.create(uri) and WebResponse but no sure how to pass in the Location class content.
I have tried JQUERY but the parameter values that were sent to the server were blanks
$(function () {
var Location = { "MyLocation": { "Name": "ABC", "Address": "123"} };
$.ajax({
type: "PUT",
url: "http://localhost/Fixit/{Id}",
data: JSON.stringify(Location),
contentType: "application/json;charset=utf-8",
processData:false,
dataType: "json",
success: function (data) {
alert("success");
},
error: function (data, status, jqXHR) {
alert("Failed: " + data.responseText);
}
});
});
How do I consume this PUT method, passing data to the Location class?
Ah, I figured it out. I had to change the Location assignment to
var Location = {"Name": "ABC", "Address": "123"};
I am calling web-api method delete all with array type parameter, showing the value null. why?
I am passing data like : data: "ArrMenuId"+ JsArrayMenuId,
function performalldeletemenu()
{
if (confirm('Are you sure you want to delete this menu?'))
{
var JsArrayMenuId = new Array();
$("input:checked").each(function ()
{
//console.log($(this).val()); //works fine
JsArrayMenuId.push($(this).val());
});
alert(JsArrayMenuId);
$.ajax({
url: '/api/MenuWebApi/DeleteAllMenu/',
type: 'DELETE',
contentType: 'application/json; charset=utf-8',
data: "ArrMenuId"+ JsArrayMenuId,
success: function (data)
{
if (data.Success == true)
{
//GetMenuList();
}
},
error: function (xhr, textStatus, errorThrown)
{
//window.location = JsErrorAction;
},
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
}
public HttpResponseMessage DeleteAllMenu(Array ArrMenuId)
{
}
Here ArrMenuId is showing null values.
if any one have solution, please let me know.
Try changing
data: "ArrMenuId"+ JsArrayMenuId,
to
data: {ArrMenuId : JsArrayMenuId.join()}
and changing
public HttpResponseMessage DeleteAllMenu(Array ArrMenuId)
to
public HttpResponseMessage DeleteAllMenu(string ArrMenuId)
I don't think javascript array will translate easily into a c# array and by changing it to this you are instead passing a string. Once you have this comma delimited string you can make it into an array in your c#
I have a form which contains a fairly large number of values. I am currently submitting with a POST method, but I wish to convert this to do it with jQuery via AJAX.
I have been experimenting with converting my code-behind "save to database" function into a Web Method. I am using a two-step function method, firstly preparing all the variables from Request.Form("parameterName") and then passing them all into a "saveData" function as follows:
<System.Web.Services.WebMethod()> _
Public Shared Sub prepareRequestFormValues()
/// save to database and do stuff with the variables
variableName = HttpContext.Current.Request("parameterName")
saveToDatabase(list, of, form, variables, ...)
End Sub
Having read this post Send form serialize to asp.net webmethod
I can see that using the jQuery forms plugin I can serialize the whole form and send it as a single variable to the processing code.
However, I have got myself completely confused now. Given that I am pretty new to AJAX/codebehind and so on I've been going round in circles and now am very confused!
Using
var queryString = $('input').fieldSerialize();
$.ajax({
type: "POST",
url: "Detail.aspx/doPostTest",
data: "{ 'txtQuery': '" + queryString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var products = eval(data.d);
console.log(products);
}
});
From the post mentioned above, I can see I can send this string, but how do I process it server-side when recieved? The article implied that HttpContext.Current.Request.Form("parameterName") should work, but it doesn't... I'm guessing because I need to access it from the txtQuery variable.... but.... I'm lost I am afraid!
Here is a really good tutorial containing the JS to do this. Instead of posting to PHP post to your aspx page. Here is an forum post with a similar question. XIII had posted the follwoing code.
<script src="../Scripts/jquery-1.6.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#btnAddToCart').click(function () {
var result = $.ajax({
type: "POST",
url: "PassInParameterAndUpdateSession.aspx/AddProductToCart",
data: '{ pID: "1833", qty: "13", lblType: "1" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: succeeded,
failure: function (msg) {
alert(msg);
},
error: function (xhr, err) {
alert(err);
}
});
});
});
function succeeded(msg) {
alert(msg.d);
}
</script>
And your WebMethod
Imports System.Web
Imports System.Web.Services
Imports System.Web.Script.Services
Namespace aspnetforums.AjaxAndSession
<ScriptService> _
Public Partial Class PassInParameterAndUpdateSession
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs)
Session("test") = ""
End Sub
<WebMethod> _
Public Shared Function AddProductToCart(pID As String, qty As String, lblType As String) As String
Dim selectedProduct As String = String.Format("+ {0} - {1} - {2}", pID, qty, lblType)
HttpContext.Current.Session("test") += selectedProduct
Return HttpContext.Current.Session("test").ToString()
End Function
End Class
End Namespace