How to pass array of objects from view to controller with AJAX - c#

I am attempting to pass an array of objects from my view to the controller with AJAX. The array is not being passed to the controller (the controller action receives null).
View:
function submitFilters() {
var filters = [];
$(".filter-option-checkbox").each( function(){
var filter =
{
FilterType: $(this).find("#filter_Type").val().toString(),
FilterDescription: $(this).find("#filter_Description").val().toString(),
OptionDescription: $(this).find("#option_Description").val().toString(),
OptionSelected: $(this).find(".custom-control-input").prop('checked')
};
filters.push(filter);
});
$.ajax({
type: 'POST',
url: '#Url.Action("Index", "Category")',
data: JSON.stringify(filters),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (view) {
},
failure: function (response) {
}
});
}
Controller:
[HttpPost]
public IActionResult Index(FilterJSON[] filters)
{
//...code here...
}
Object Classes:
public class FilterJSON
{
public string FilterType { get; set; }
public string FilterDescription { get; set; }
public string OptionDescription { get; set; }
public bool OptionSelected { get; set; }
}
I don't think I'm far off. What am I missing? Thank you.

[HttpPost]
public IActionResult Index([FromBody]FilterJSON[] filters)
{
//...code here...
return null;
}
and
$.ajax({
type: 'POST',
url: '#Url.Action("Index", "Home")',
data: JSON.stringify(filters),
contentType: "application/json; charset=utf-8",
success: function (view) {
},
failure: function (response) {
}
});
should work

You need to use a ViewModel with a List inside:
public class YourViewModel
{
public List<FilterJSONItem> FilterJSON{ get; set; }
}
public class FilterJSONItem
{
public string FilterType { get; set; }
public string FilterDescription { get; set; }
public string OptionDescription { get; set; }
public bool OptionSelected { get; set; }
}
public ActionResult Method([FromBody]YourViewModel vm)
{
}

Related

How to get each value from table in ASP.NET MVC?

I get each value but it doesn't display on DSChiTiet. How can I fix it? It only gets value TenKH, NgayLap, TongTien.
DSChiTiet doesn't get value from table and displays null. enter image description here
Thank you very much for your help <3.
My model PhieuBanHangModel
public class PhieuBanHangViewModel
{
public int MaPBH { get; set; }
public string TenKH { get; set; }
public DateTime NgayLap { get; set; }
public decimal TongTien { get; set; }
public IEnumerable<CT_PhieuBanHangViewModel> DSChiTiet { get; set; }
}
My model CT_PhieuBanHangModel
public class CT_PhieuBanHangViewModel
{
public int MaPBH { get; set; }
public int MaSP { get; set; }
public int SoLuong { get; set; }
public decimal DonGia { get; set; }
public decimal ThanhTien { get; set; }
}
Controller Create Json
[HttpPost]
public JsonResult Create(PhieuBanHangViewModel phieuBanHang)
{
return Json(data: "", JsonRequestBehavior.AllowGet);
}
Function in View
function ThanhToan() {
var phieuBanHang = {};
var dsct_PhieuBanHang = new Array();
phieuBanHang.TenKH = $("#txtTenKH").val();
phieuBanHang.NgayLap = $("#txtNgayGiaoDich").val();
phieuBanHang.TongTien = $("#txtTongTien").val();
$("table tr:not(:first)").each(function () {
var ct_PhieuBanHang = {};
ct_PhieuBanHang.MaSP = parseFloat($(this).find("td:eq(0))").text());
ct_PhieuBanHang.SoLuong = parseFloat($(this).find("td:eq(4))").text());
ct_PhieuBanHang.DonGia = parseFloat($(this).find("td:eq(6))").text());
ct_PhieuBanHang.ThanhTien = parseFloat($(this).find("td:eq(7))").text());
dsct_PhieuBanHang.push(ct_PhieuBanHang);
});
phieuBanHang.DSChiTiet = dsct_PhieuBanHang;
$.ajax({
async: true,
type: 'POST',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(phieuBanHang),
url: '/Manager/CT_PhieuBanHang/Create',
success: function (data) {
},
error: function () {
alert('Lỗi');
}
});
}
You may need to inherit ApiControllerand add the [FromBody] attribute to the binding model:
public class MyController : ApiController
{
/* something else... */
// /Manager/CT_PhieuBanHang/Create
[HttpPost]
public JsonResult Create([FromBody] PhieuBanHangViewModel phieuBanHang)
{
return Json(data: "", JsonRequestBehavior.AllowGet);
}
/* something else... */
}
For your jQuery code, make sure thet:$("table tr:not(:first)") do returns an array contains at least 1 item. (You can verify that by doing a console.log(phieuBanHang) to print out your data).

Send Model With Json In Asp.net Core

I want to pass the model from controller to Success method in View and access the properties from the model with json. How do I write and how to access the properties in Success method?
public async Task<IActionResult> Edit( Department department)
{
if (ModelState.IsValid)
{
_genericRepository.Update(department);
await _genericRepository.SaveChangesAsync();
var model = _genericRepository.GetByIdAsync(department.Department_Id);
return Json(new { Message = model });
}
return Json(department);
}
<script>
function Success(data)
{
alert(data.Messge);
}
function Failure() {
}
</script>
How about:
$.ajax({
url: "<path>/Edit",
type: "POST",
data: JSON.stringify(department),
dataType: "json",
cache: false,
success: function (data) {
[...]
},
error: function () {
[...]
}
})
You can access data list from json file when using Json.Parse();
<script>
function Success(data)
{
var getDataList = Json.parse(data);
alert(getDataList);
}
function Failure() {
}
</script>
public ActionResult Import()
{
string response = JsonConvert.SerializeObject(responseModel);
return this.Content(response);
}
class ResponseModel
{
public string bodyone { get; set; }
public string bodytwo { get; set; }
public string HeadersFile1 { get; set; }
public string HeadersFile2 { get; set; }
public string FileName1 { get; set; }
public string FileName2 { get; set; }
}
then parse the response using JSON parser. Now you can read property values from ajax success like this
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
var obj = JSON.parse(response);
$('#divPrint').html(obj.bodyone);
$('#divPrint2').html(obj.bodytwo);
$('#fileName1').html(obj.FileName1);
$('#fileName2').html(obj.FileName2);
$('#headersFile1').html(obj.HeadersFile1);
$('#headersFile2').html(obj.HeadersFile2);
}
}

Saving data with json in custom class

I'm still trying to understand this ajax.
I'm trying to save the Patient from js to the database on the serverside, but the code below always result in [alert("error")]
Can someone see the mistake?
MVC action:
public JsonResult CreatePatient(string patient)
{
var jsonPatient = JsonConvert.DeserializeObject<Patient>(patient);
if (db.Patients.Contains(jsonPatient))
{
db.Patients.Remove(jsonPatient);
}
db.Patients.Add(jsonPatient);
return new JsonResult();
}
Custom class:
public class Patient
{
[Key]
public string Cpr { get; set; } //ID
private string _firstname;
private string _lastname;
//public List<TestReceving> TestHandelings { get; set; }
public string Firstname
{
get { return _firstname; }
set { _firstname = value; }
}
public string Lastname
{
get { return _lastname; }
set { _lastname = value; }
}
public override bool Equals(object obj)
{
return obj is Patient ? Cpr == (obj as Patient).Cpr : false;
}
}
js:
function savePatient() {
var Patient = {
Cpr: $("#cpr").val(),
Lastname: $("#lastname").val(),
Firstname: $("#firstname").val()
};
var dataToPost = JSON.stringify(Patient);
$.ajax({
type: "POST",
url: "/Patient/CreatePatient",
contentType: "application/json; charset=utf-8",
data: dataToPost,
dataType: "json",
success: function () {
// do what you want on success.
alert("saved");
},
error: function () {
alert("error");
}
});
}
I have changed it to:
public JsonResult CreatePatient(Patient patient)
{
if (db.Patients.Contains(patient))
{
db.Patients.Remove(patient);
}
db.Patients.Add(patient);
return new JsonResult();
}
and
function savePatient() {
var Patient = {
Cpr: $("#cpr").val(),
Lastname: $("#lastname").val(),
Firstname: $("#firstname").val()
};
$.ajax({
type: "POST",
url: "/Patient/CreatePatient",
contentType: "application/json; charset=utf-8",
data: Patient,
dataType: "json",
success: function () {
// do what you want on success.
alert("saved");
},
error: function () {
alert("error");
}
});
}
But I am still getting the error.
You dont need to JSON.stringify, just send Patient as is:
data: Patient,
and recieve in action:
public JsonResult CreatePatient(Patient patient)
{
...
}
Update: while sending raw json (not stringified) contentType: "application/json" should not be used.
Add [HttpPost] attribute on the method body like
[HttpPost]
public JsonResult CreatePatient(Patient patient){...}

how to pass list of objects that contains another list of object to wcf

I have class contain list of object of another class.But when i send list of object to wcf method it coming about null.
here is my full code
here is my class :-
public class BOTHCCharges_DETAILS
{
public String THCTerm { get; set; }
public String FromNumberOfContainer { get; set; }
public String ToNumberOfContainer { get; set; }
public String _20_GP { get; set; }
public String _20_HC { get; set; }
public String _40_GP { get; set; }
public String _40_HC { get; set; }
public String Size { get; set; }
public String Weight { get; set; }
}
[DataContract]
[KnownType(typeof(List<BOTHCCharges_DETAILS>))]
public class List_BOTHCCharges_DETAILS
{
[DataMember]
public List<BOTHCCharges_DETAILS> THC_Details { get; set; }
}
//**** ICharges.cs
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "AddTHCCharges")]
String AddTHCCharges(BOTHCCharges_Master OBJBOTHCCharges_Master, List<List_BOTHCCharges_DETAILS> List_BOTHCCharges_DETAILS);
//*** Charges.svc.cs
public string AddTHCCharges(BOTHCCharges_Master OBJBOTHCCharges_Master, List<List_BOTHCCharges_DETAILS> List_BOTHCCharges_DETAILS)
{
//code goes here.
}
this is the json object i am sending through jquery ajax
{
"OBJBOTHCCharges_Master":
{
"OriginLocationList":"[{\"CountryCode\":\"CHINA,\",\"LocationCode\":\"CNSHA,\",\"Currency\":\"AED,\"}]",
"DesinationLocationList":"[{\"CountryCode\":\"SIN,\",\"LocationCode\":\"SGSIN,\",\"Currency\":\"AED,\"}]",
"CargoWeight":"20,","CargoType":"Consol,General,","Taxable":true,"TradeType":"E"},
"List_BOTHCCharges_DETAILS":
[
["THC_Details",
{
"THCTerm":"","FromNumberOfContainer":"","ToNumberOfContainer":"","_20_GP":"","_20_HC":"","_40_GP":"","_40_HC":"","Size":"20","Weight":"Consol"
},
{
"THCTerm":"","FromNumberOfContainer":"","ToNumberOfContainer":"","_20_GP":"","_20_HC":"","_40_GP":"","_40_HC":"","Size":"20","Weight":"Consol"
}
],
["THC_Details",
{
"THCTerm":"","FromNumberOfContainer":"","ToNumberOfContainer":"","_20_GP":"","_20_HC":"","_40_GP":"","_40_HC":"","Size":"26","Weight":"Consol"
}
]
]
}
jquery call
var wcfServiceUrl = THC.urlAddTHCCharges;
$.ajax({
cache: false,
url: wcfServiceUrl,
data: data,
type: 'POST',
contentType: 'application/json',
dataType: 'json',
beforeSend: function () {
//fnBlockUI('operation in progress..', 'false', 'true', 'null', false);
},
success: function (data) {
if (data.AddTHCChargesResult == 'SUCCESS') {
//$.showMessageBox({ content: "data has been saved successfully", title: 'My information' });
$.showMessageBox({ content: "Data has been saved successfully!", title: 'Save', OkButtonDoneFunction: function () {
location.href = 'Index'
}, type: 'question'
});
}
else {
$.showMessageBox({ content: data.AddDetentionChargesResult, title: 'Error', type: 'stop' });
}
},
error: function (error) {
$.showMessageBox({ content: error.responseText, title: 'Stop', type: 'stop' });
},
complete: function () {
//$.unblockUI();
}
});
*/
Class that container list of another class(class member) coming out null :-
click to view for your reference.
Do i need to serialised my class members or what ?.I am new to wcf.
Your JSON does not match your class.
This
public class List_BOTHCCharges_DETAILS
{
[DataMember]
public List<BOTHCCharges_DETAILS> THC_Details { get; set; }
}
means this
{ "THC_Details": [ { "THCTerm":"", … }, … ] }
not this
{ [ "THC_Details", { "THCTerm":"", … } ], … }
If the JSON does not match the class definition, you'll get a null as the binder is unable to deserialize the payload.

Object not received in Backend POST method as sent through $.ajax

The problem is that I am sending an object array in correct format through $4.ajax to a POST method in MVC, but on the backend it is not receiving as expected. If I send an Array of 3 objects, it shows that the backend object is received as a List of 3 objects, but the attributes in those objects are not loaded properly. Infact, none of the values are copied.
Here is the relevant javascript code
var array = new Array();
for (var i = 0 ; i < $('.TourCommission:enabled').length; i++)
{
var data = {
TourCodeID: parseInt($('.TourCommission:enabled').eq(i).parent().prev().html()),
Commission: parseFloat($('.TourCommission:enabled').eq(i).val())
};
array.push(data);
}
$.ajax({
url: '/Booking/submitAgentTourCommissions',
data: JSON.stringify(array),
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('form').submit();
},
error: function () {
return true;
}
});
Here is the backend code
[HttpPost]
public JsonResult submitAgentTourCommissions(List<AgentTourCommission> obj) {
return Json(true);
}
The AgentTourCommission class is as below
public class AgentTourCommission
{
public int UserID;
public string UserName;
public int TourCodeID;
public string TourCodeName;
public float Commission;
}
screenshot of Javascript Watch
screenshot of BackEnd Watch
You need add the get set like this:
public class AgentTourCommission
{
public int UserID { get; set; }
public string UserName { get; set; }
public int TourCodeID { get; set; }
public string TourCodeName { get; set; }
public float Commission { get; set; }
}
I hope you help!

Categories

Resources