Null value when passing value from ajax to MVC controller - javascript

I have a value that I want to pass to MVC action,
here is the JS side
function functionName(Name) {
$.ajax({
url: "/Home/GetName",
type: "POST",
dataType: "json",
data:JSON.stringify({
Name: Name
}),
success: function (mydata) {
}
});
return false;
}
and here is my action
[HttpPost]
public JsonResult GetName(string Name)
{
return Json(new { oid = Name});
}
Noting that I successfully print the value "Name" before I send it to the action, but the action is receiving it as a "null"

Stephen "in the comments" is correct
the solution is
changing this
data:JSON.stringify({
Name: Name
}),
to
data: { Name: Name }

Try by adding
contentType: "application/json"
as belove
function functionName(Name) {
$.ajax({
url: "/Home/GetName",
type: "POST",
dataType: "json",
contentType: "application/json",
data:JSON.stringify({
Name: Name
}),
success: function (mydata) {
}
});
return false;
}
Hope this will help you, :)

Related

How To Post Json Data To Controller Without a Model in .net core

There is a huge data stored in grid that comes from a sql query joined more than ona table. Data type is Json. I filtered data and then want to sent filtered data to controller. But how it can be?
Here is test json data in javascript block:
var jsonData = {
"FirstName": "John",
"LastName": "Doe",
"DoB": "01/01/1970" };
And this is my javascript function:
function submitForm() {
var user = jsonData;
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(user),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
How to get the Json data in controller? Here is my [HttpPost] method:
[HttpPost]
public IActionResult GetJsonData(String user)
{
//...
return null;
}
user gets null.. Should i change type "String" in method or something else?
Since user is a string, you could try to create an object with a property user:
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
user: JSON.stringify(user)
},
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
Or using FormData:
var formData = new FormData();
formData.append('user', JSON.stringify(user));
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
contentType: false,
processData: false,
data: formData,
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});

ASP.NET MVC - How to pass a Javascript variable from view to controller

I have a variable in a javascript function which needs to be sent to the controller. This is the code in the javascript function.
var testString = "Test";
$.ajax({
type: "POST",
url: "#Url.Action("GetJavaScriptString")",
dataType: "json",
data: JSON.stringify(testString),
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
And this is the controller method
public ActionResult GetJavaScriptString(string data)
{
return null;
}
The variable "data" in the GetJavaScriptString method remains null.
You need to send a name/value pair when the name matches the name of your parameter
var testString = "Test";
$.ajax({
type: "POST",
url: "#Url.Action("GetJavaScriptString")",
dataType: "json",
data: { data: testString }, // change this
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
Note that you do not need JSON.stringify(), but if you did it would be data: JSON.stringify({ data: testString }), and you would need to the contentType: 'application/json', option

Ajax Not Working With C# Controller Action With 2D Array Parameter

My Ajax is not hitting my controller action. What could be the reason?
My Controller Action
public ActionResult Save_Data(string [][] rosterArray, int Pricelist_Id, int Group_Id)
My Ajax
$.ajax({
url: '#Url.Action("Save_Data", "PriceListMaster")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: { "rosterArray": rosterArray, "Pricelist_Id": "2", "Group_Id": $("#Group_Id").val() },
//data: JSON.stringify({ "Item_Code": Item_Code, "IPD_Price": IPD_Price, "OPD_Price": OPD_Price, "EMS_Price": EMS_Price }),
success: function (data) {
debugger
if (data.success)
{
alert('Data Saved Successfully.');
location.reload();
} else {
alert(data.error_msg);
}
}
}
If you are using type: 'Post' in AJAX, that means you need to add a Request type in Controller.
Try using this in controller,
[HttpPost]
public ActionResult Save_Data(string [][] rosterArray, int Pricelist_Id, int Group_Id)
Use httpPost in the Method for define type of response.
at client side
$.ajax({
url: '#Url.Action("Save_Data", "PriceListMaster")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: { "rosterArray": JSON.stringify(rosterArray), "Pricelist_Id": "2", "Group_Id": $("#Group_Id").val() },
//data: JSON.stringify({ "Item_Code": Item_Code, "IPD_Price": IPD_Price, "OPD_Price": OPD_Price, "EMS_Price": EMS_Price }),
success: function (data) {
debugger
if (data.success)
{
alert('Data Saved Successfully.');
location.reload();
} else {
alert(data.error_msg);
}
}
}
and your controller code can be like this:
[HttpPost]
public ActionResult Save_Data(string rosterArray, int Pricelist_Id, int Group_Id)
{
string [][] convertedArray = JsonConvert.DeserializeObject<string [][]>(rosterArray);
}
Hope this works
Note: But you need to incude using Newtonsoft.Json;

ASP.NET WebMethod returns whole page to JQuery ajax requests

I am building a web application where I am calling a ASP.NET WebMethod from jQuery on click of a textbox. The problem is that it returns me the whole ASPX Page. How can I get just the values returned by the Web Method? This is my code:
$("#<%= groupNameTxt.ClientID %>").click(function () {
$.ajax({
url: "../UserGroups.aspx/GetGroupList",
data: "{ }",
// dataType: "json"
type: "POST",
// contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
});
This is my WebMethod from CodeBehind
[System.Web.Services.WebMethod]
public static List<Groups> GetGroupList(string mail)
{
List<Groups> empList = new List<Groups>();
empList.Add(new Groups() { GroupID = 1, GroupName = "Admins" });
empList.Add(new Groups() { GroupID = 2, GroupName = "Employees" });
empList.Add(new Groups() { GroupID = 3, GroupName = "Engineers" });
empList.Add(new Groups() { GroupID = 4, GroupName = "Managers" });
empList.Add(new Groups() { GroupID = 5, GroupName = "Assistants" });
return empList;
}
You need to pass email as parameter as webmethod is expecting a parameter.
$.ajax({
url: "../UserGroups.aspx/GetGroupList",
data: JSON.stringify({ email: "someemail#test.com"}),
dataType: "json"
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
Also specify contentType and dataType
The page was returning since it was not hitting the Web Method. The below code will hit the Web Method correctly. Pass in data as shown below.
$.ajax({
url: "UserGroups.aspx/GetGroupList",
data: '{ mail: "a#a.com"}',
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});

How to call ASP.net web method with Array parameter from jQuery Javascript?

I have the following ASP.net web method:
[WebMethod]
public static string SaveUserNew(string id, string[] roles)
{
doStuff(id, roles);
}
I'm calling this code from jQuery Javascript code, but I don't know the syntax for passing an array. Ordinarily, I write jQuery code to call web methods that looks like this:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: '{"foo":"fooValue"}',
contentType: "application/json;",
dataType: "json",
}
Please shed some light on this.
Update: Here is an example of code without arrays that does work:
[WebMethod]
public static string SaveUserNew(string id)
{
return "0";
}
var jdata = '{ "id": "3TWR3"}';
$.ajax({
type: "POST",
url: "UserMgmt.aspx/SaveUserNew",
data: jdata,
contentType: "application/json;",
dataType: "json",
traditional: true
}
});
My intention is to write some code in a similar style where I pass arrays to my web method.
Passing param to webmethod is a little bit tricky. Try this one
[WebMethod]
public static string GetPrompt(string[] name)
{
return "Hello " + name[0] + " and " + name[1];
}
jscript
var param = "{'name':['jack', 'jill']}";
var option = {
error: function(request, status, error) {
alert(error);
},
cache: false,
success: function(data, status) {
alert(data.d);
},
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
url: "../Server/ArrayParam.aspx/GetPrompt"
};
$.ajax(option);
You need to
1) assign the data parameter to have an object with the properties id and roles.
2) assign the roles property an array of strings.
3) Set the traditional setting to true while passing options to ajax call.
e.g:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: {
"id":"1",
"roles":[
"Admin",
"Something",
"Another Thing"
]
},
contentType: "application/json;",
dataType: "json",
traditional: true //#############################
}

Categories