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){...}
Related
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)
{
}
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);
}
}
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.
I am getting below error when I execute my Ajax JQuery:
Below is the code I am using:
IPRRequest.cs class code(.dll)
public static bool IsValidBarcodeTest(Guid? requestID, string barCode)
{
bool result = true;
Dictionary<string, object> input = new Dictionary<string, object>() {
{"#RequestID", requestID},
{"#BarcodeNo", barCode}
};
Data data = new Data();
DataTable dt = data.ExecuteQuery(CommandType.StoredProcedure, "Invoice.usp_tbl_Request_Select_CheckDuplicateBarcode_Test", input);
if (dt.Rows.Count > 0)
{
result = Helper.GetDBValue<int>(dt.Rows[0][0]) == 0;
}
return result;
}
.aspx.cs page code:
public abstract class Check
{
public abstract Guid? requestID { get; set; }
public abstract string barCode { get; set; }
}
[WebMethod]
[ScriptMethod]
public static bool CheckDuplicate(Check chk)
{
bool isExist = false;
isExist = IPRRequest.IsValidBarcodeTest(chk.requestID, chk.barCode);
return isExist;
}
Ajax JQuery code:
<script type="text/javascript">
$(document).ready(function () {
$("[id*=btnSave]").bind("click", function () {
var chk = {};
chk.requestID = $("[id*=TempGUID]").text();
alert(chk.requestID);
chk.barCode = $("[id*=txtBarcodeNumber]").val();
alert(chk.barCode);
$.ajax({
type: 'POST',
url: "IPRForm_EditCheck.aspx/CheckDuplicate",
data: '{chk: ' + JSON.stringify(chk) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
var val = data.d;
alert(val);
if (val == true) {
alert("Barcode Number already exist in system database.");
}
else {
alert("Barcode Number does not exist");
}
},
error: function (data) {
alert(data.responseText);
},
});
return false;
});
});
</script>
Stored Procedure
Select
Case When count(1) > 0
Then 1 --Exist
Else 0 --Not Exist
End As Duplicate
From Invoice.tbl_Request(NOLOCK)
Where BarcodeNo = #BarcodeNo
And (#RequestID Is Null Or RequestID <> #RequestID)
Please reply what is wrong in my code.
Please note that I am very new in Ajax JQuery and Web Method
Thanks in advance.
.NET needs to create an object of type Check to pass as a parameter to the WebMethod CheckDuplicate.
It cannot create an object of an abstract class.
If you change class Check to the following, it should work:
public class Check
{
//This constructor is needed, but .NET will create
//it automatically if no other constructors are defined
public Check() { }
private Guid? requestID;
private string barCode;
public Guid? RequestId
{
get { return requestID; }
set { requestID = value; }
}
public string BarCode
{
get { return barCode; }
set { barCode = value; }
}
}
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!