my model:
public class Hello
{
public List<string> name;
public List<string> phone;
public List<string> contact;
}
my controller code is
public ActionResult Home(Hello obj) // obj is coming out to be null
{
}
my script is
var names =[];
var phones =[];
var contacts = [];
// some code to fill the arrays
var obj = [{
name: names,
phone: phones,
contact: contacts,
}];
debugger;
$.ajax({
cache: false,
url: 'Home',
data: { obj:obj },
success: function (data) {
var response = JSON.parse(data);
window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
i can see in the debugger that data is stored in the arrays but when i am sending data to controller the obj is null can someone suggests where am i going wrong ?
You have object in code behind so do not pass array of Hello object.
And also use POST request because GET request have not message body.
Please use below
var obj = {
name: ['1', '2', '3'],
phone: ['234324', '34343243', '3434234234'],
contact: ['Test1', 'Test2', 'Test3']
};
debugger;
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'Home',
data:JSON.stringify({ obj: obj }),
success: function (data) {
var response = JSON.parse(data);
// window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
public class Hello
{
public List<string> name { get; set; }
public List<string> phone { get; set; }
public List<string> contact { get; set; }
}
Actually i solved the problem , i had to set
traditional:true,
in my ajax call
Related
I want to pass multiple key and value pair of dictionary type from client side using post method to server side which is MVC Web API HTTP get method.
function FileSenderAPI(){
var DictionaryData = new Object;
DictionaryData = document.getElementById("hidFilePath").value;
var Url = '<%=System.Configuration.ConfigurationManager.AppSettings["FileSenderAPI"].To String() %>';
$.ajax({
url: Url,
method: 'Get',
data Type: "json",
data: {
ModelsPath:JSON.stringify(DictionaryData),
Exchange: exchange,
Exchange_key: key,
},
success: function (data, textStatus, xhr) {
alert(data);
},
}
public HttpResponseMessage ConvertModel(Dictionary<string, string> ModelsPath,string Exchange,string Exchange_key)
{
} // its my API method.``
Here is a solution. You can try it. Hope to help, my friend :))
1) Create a model
public class DictionaryModel
{
public Dictionary<string, string> dict { get; set; }
public string Exchange { get; set; }
public string Exchange_Key { get; set; }
}
2) Action
[HttpPost]
public JsonResult Example(DictionaryModel model)
{
// Your Logic
return Json("Success");
}
3) In View
$('#btClick').on('click', function () {
var dict = {};
dict["id"] = "200";
dict["Name"] = "Chris";
dict["DynamicItem1"] = "Item 1";
var theObject = {};
theObject.dict = dict;
theObject.Exchange = "Abc";
theObject.Exchange_Key = "123";
let url = '#Url.Action("Example","Home")';
$.post( url, theObject, function (data, textStatus, XMLHttpRequest) {
console.log("success");
}, "json");
});
i write web api.
web api controller:
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask(string xx,string yy,CommonTask Task)
{
...
}
}
and ajax:
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"xx":'admin',"yy":'123',"task": JSON.stringify(task) },
type: 'Post',
success: function (data) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
and WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
when run ajax, return error:
No action was found on the controller 'TaskApi' that matches the request
Always feed the POST methods with class type parameters. Please do the following modification on the API and JavaScript.
1. Create a model class
<pre>
public class Model
{
public string xx { get; set; }
public string yy { get; set; }
public CommonTask Task { get; set; }
}
</pre>
Then modify your Web API to accept a type of your class model
<pre>
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask([FromBody] Model model)
{
}
}
</pre>
Change your ajax method to pass a json object similar to the Model class
<pre>
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var data = {
"xx": 'admin',
"yy": '123',
"task" : JSON.stringify(task)
};
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"model": JSON.stringify(data) },
type: 'Post',
success: function (message) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
</pre>
so here is my problem, I am returning a list of my model List from a controller through ajax. In response I am getting List but when i try to fill my datatable with this response it shows undefined everywhere
My View:
function GetData() {
pid = $(this).data('id');
var singleValues = $("#network").val();
var id = $(this).find(":selected").val();
var network = { "network": id };
$.ajax({
type: 'POST',
url: '/Home/GetData',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(network),
success: function (response) {
// console.log(response);
alert(response);
for (var i = 0; i < response.d.length; i++) {
$("#example").append("<tr><td>" + response.d[i].ACCOUNT_TYPE_ID + "</td><td>" + response.d[i].ACCOUNT_ISO_CODE + "</td><td>" + response.d[i].ACCOUNT_DESC + "</td></tr>");
debugger;
}
}
});
MY Controller:
[HttpPost]
public DbDataModel[] GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
DataTable db = GetDataSource(network);
foreach (DataRow row in db.Rows)
{
DbDataModel model = new DbDataModel();
model.Account_type_id = row["ACCOUNT_TYPE_ID"].ToString();
model.Account_iso_code = row["ACCOUNT_ISO_CODE"].ToString();
model.Account_desc = row["ACCOUNT_DESC"].ToString();
l.Add(model);
}
return l.ToArray();
}
My Model:
public class DbDataModel
{
public string Account_type_id { get; set; }
public string Account_iso_code { get; set; }
public string Account_desc { get; set; }
}
Change your method to return JSON
[HttpGet]
public JsonResult GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
.....
return Json(l, JsonRequestBehavior.AllowGet);
}
and in the script
...
$.ajax({
type: 'GET',
...
This is how i got it right.
function GetData() {
pid = $(this).data('id');
var singleValues = $("#network").val();
var id = $(this).find(":selected").val();
var network = { "network": id };
$.ajax({
type: 'POST',
url: '/Home/GetData',
dataType:"json",
traditional: true,
data: jQuery.param( network ),
success: function (response) {
debugger;
var oTable = $('#example').dataTable();//get the DataTable
oTable.fnClearTable();//clear the DataTable
for (var i = 0; i < response.length; i++) {
// $("#example").append("<tr><td>" + response[i].Account_type_id + "</td><td>" + response[i].Account_iso_code + "</td><td>" + response[i].Account_desc + "</td></tr>");
oTable.fnAddData([
response[i].Account_type_id,
response[i].Account_iso_code,
response[i].Account_desc
]);
}
}
});
};
[HttpPost]
public ActionResult GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
DataTable db = GetDataSource(network);
foreach (DataRow row in db.Rows)
{
DbDataModel model = new DbDataModel();
model.Account_type_id = row["ACCOUNT_TYPE_ID"].ToString();
model.Account_iso_code = row["ACCOUNT_ISO_CODE"].ToString();
model.Account_desc = row["ACCOUNT_DESC"].ToString();
l.Add(model);
}
return Json(l.ToArray(), JsonRequestBehavior.AllowGet);
}
Doing exactly what I wanted.
I am using Ajax with MVC4 web application. I've got a problem with passing values to action method. It's always pass the null as the parrameter value.
Here is my codes.
function onChange(arg) {
var adrId = $.map(this.select(), function (item)
{
return $(item).find('td').first().text();
});
GetEntries(adrId);//Calling the function
}
function GetEntries(adrId) {
//alert("AdrId >> "+adrId); here it shows value is 3465
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ adrId: adrId }),
success: function (result) {
alert("success");
}
});
}
[HttpPost]
public JsonResult LoadCustomer(string adrId)//HERE value is ALLWAYS NULL.. :(
{
Address_SelectW adrList = new Address_SelectW();
adrList = this.commonObj.CustomersSelectByAdrKy(cky, usrKy, AdrKy);
return Json(adrList, JsonRequestBehavior.AllowGet);
}
Please help me to solve this problem. Thank you.. :)
===========================================================================
Additional Informations....
I have used another one to insert data. it's worked fine..
$("#btnSave").click(function () {
//var ContactID = $("#txtContactId").val();
var Company = $("#txtCompany").val();
var Status = $("#cmbStatus").val();
var IsActive = $("#IsActive").is(':checked');
var Comments = $("#txaComments").val();
var Country = $("#cmbCountry").val();
var Address1 = $("#txtAddress1").val();
//var Address2 = $("#txtAddress2").val();
var City = $("#txtCity").val();
var State = $("#txtState").val();
var PostalCode = $("#txtPostalCode").val();
var VatNo = $("#txtVatNo").val();
var RegNo = $("#txtRegNo").val();
var Phone = $("#txtPhone").val();
var Email = $("#txtEmail").val();
var AdrKey = $("#AdrID").val();
$.ajax({
url: "Customer/InsertCustomer",
data: {
//'ContactID': ContactID,
'Company': Company,
'Status': Status,
'IsActive': IsActive,
'Comments': Comments,
'Country': Country,
'Address1': Address1,
//'Address2': Address2,
'City': City,
'State': State,
'PostalCode': PostalCode,
'VatNo': VatNo,
'RegNo': RegNo,
'Phone': Phone,
'Email': Email
},
dataType: "json",
type: 'POST',
success: function (data) {
alert("Successfully Inserted!");
},
error: function () {
alert("error");
}
});
});
[HttpPost]
public ActionResult InsertCustomer(string Company, int Status, bool IsActive, string Comments, int Country, string Address1, string City, string State, string PostalCode, string VatNo, string RegNo, string Phone, string Email)
{
AdrCustomModel model = new AdrCustomModel();
bool process = false;
model.Company = Company;
model.Status = Status;
model.IsActive = IsActive;
model.Comments = Comments;
model.Country = Country;
model.Address1 = Address1;
model.City = City;
model.State = State;
model.PostalCode = PostalCode;
model.VatNo = VatNo;
model.Phone = Phone;
model.RegNo = RegNo;
model.Email = Email;
model.cky = cky;
model.ContactID = this.CustomerID(Status);
process = this.commonObj.InsertAdrCustomer(model,usrKy);
Accounts_Select accmodel = new Accounts_Select();
accmodel.CKy = cky;
accmodel.AccCd = model.ContactID;
accmodel.AccNm = Company;
accmodel.AccTypKy = this.commonObj.AccTypeKyByPrefixKy(Status);
process = this.commonObj.InsertAccount(accmodel, usrKy);
return Json(process, JsonRequestBehavior.AllowGet);
}
I have no idea about why this one is working fine and that one is not working. I have tried both JsonResult and ActionResult to Action method. And also tried with and without [HttpPost].
But always Parrameter value is NULL
I'm not sure if it will solve your problem but you can try this.
Place [WebMethod] attribute in your controller method.
or you can you can pass url with appended id like
'Customer/LoadCustomer'+ adrId
Put the property name in quotes:
data: JSON.stringify({ 'adrId': adrId }),
In your first example, you send a JSON object, in the second you just post data.
JSON is unnecessarily complicated to send just one value. Try this instead:
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
data: {'adrId': adrId },
dataType: 'json',
success: function (result) {
alert("success");
}
});
It required concatenate "" with the parameter which you wanna pass to Action method.
function GetEntries(adrId) {
var NewAdrId = ""+adrId; //<<<<<<<<<<<< Answer<<<<<<<<<<<<<<
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ adrId: NewAdrId }),
success: function (result) {
alert("success");
}
});
}
// Thanks :)
on MVC3 Page load i have a String in a Model which is should be the JSONObj.
private string CreateJSONObj(Model model)
{ return "{ name: 'test', Items: [{ test: 1 }, { test: 2 }]"; }
Model.jsonModel = CreateJSONObj(model);
Now i want to implement it in my page:
<script>var jsModel = eval('#Model.jsonModel');
var jsonModel = $.toJSON(jsModel);
$.ajax({
url: 'Page/SetJSON/',
type: "POST",
data: jsonModel,
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$('#test').html('Saved').fadeIn(),
},
error: function () {
$("#test").html("error"),
}
});</script>
But the Controller gets a null Object. If i write the jsonstring into the script everthing is fine.
Should i use eval? But var jsModel = eval('#Model.jsonModel'); has no effect. What is wrong? :-)
You don't need to use a CreateJSONObj method or a jsonModel property on your model. In order to use it in the view you could simply use the JavaScriptSerializer class which will convert the server side model object into a javascript object:
<script type="text/javascript">
var jsModel = #Html.Raw(new JavaScriptSerializer().Serialize(Model));
$.ajax({
url: '#Url.Action("SetJSON", "Page")',
type: 'POST',
data: JSON.stringify(jsModel),
contentType: 'application/json; charset=utf-8',
success: function () {
$('#test').html('Saved').fadeIn();
},
error: function () {
$('#test').html('error');
}
});
</script>
This will successfully send the model to the following controller action:
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
where the Model class contains all the necessary information:
public class Model
{
public string Name { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public int Test { get; set; }
}
and the controller:
public class PageController: Controller
{
// Used to render the view
public class Index()
{
var model = new Model
{
Name = "Test",
Items = new[]
{
new Item { Test = 1 },
new Item { Test = 2 },
}
};
return View(model);
}
// Used to handle the AJAX POST request
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
}