I am working on two web method And I want to access one filed from another web Method and I am not sure how can it will be possible.
I want to call DivisionCode in another web method is it possible ?
WebMethod1 Getcompanies :
From this web method i want to get DivisionCode = company.DivisionCode and will pass into another web method as a parameter
[WebMethod]
public static List<Company> Getcompanies(string Countrycode, string Companycode)
{
GetInitiatorList.MasterDataServiceClient oClient = new GetInitiatorList.MasterDataServiceClient();
Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M[] initiatorslist = oClient.GetCompanies(Countrycode, Companycode);
//almarai.giveaway.getinitiatorlist.alm_company_m[] companymlist = initiatorslist.companies;
List<Company> companyes = new List<Company>();
foreach (Almarai.GiveAway.GetInitiatorList.ALM_COMPANY_M company in initiatorslist)
{
companyes.Add(new Company()
{
CompanyCode = company.CompanyCode,
CompanyName = company.CompanyName,
DivisionCode = company.DivisionCode
});
}
return companyes;
}
Respected class:
public class Company
{
public string CompanyCode { get; set; }
public string CompanyName { get; set; }
public string DivisionCode { get; set; }
}
WebMethod 2 GetDivision
This is my second web Method and i want to pass FirsrWebMethod field to another web method ( DivisionCode = company.DivisionCode )
[WebMethod]
public static List<Devision> GetDivision(string Countrycode, string Companycode)
{
string Divisi = string.Empty;
var v = new Company();
v.DivisionCode = Divisi; //v.DivisionCode returning "" (Empty string)
GetInitiatorList.MasterDataServiceClient oClient = new GetInitiatorList.MasterDataServiceClient();
// Almarai.GiveAway.GetInitiatorList.INITIATORS_LIST initiatorsList = oClient.GetInitiatorsListByWorkflow(userid, work);
Almarai.GiveAway.GetInitiatorList.ALM_DIVISION_M[] divisionMList = oClient.GetActiveDivisions(Countrycode, Companycode, Divisi) ;
//GetActiveDivisions Expecting three parameters including divisionCode
List<Devision> Division = new List<Devision>();
foreach (Almarai.GiveAway.GetInitiatorList.ALM_DIVISION_M Devision in divisionMList)
{
Division.Add(new Devision()
{
DevisionCode = Devision.DivisionCode,
DevisionName = Devision.DivisionName
});
}
return Division;
}
Respected Class:
public class Devision
{
public string DevisionCode { get; set; }
public string DevisionName { get; set; }
}
JS
$('#ddlCompany').change(function (e) {
BindDivision();
});
BindCompanies:
function BindCompanies() {
var countrycode = $('#ddlCountry').val();
$('#ddlCompany').empty();
if (countrycode == 'OMN') {
Companycode = '7000';
}
else if (countrycode == 'SAU') {
Companycode = '1000';
}
else if (countrycode == 'UAE') {
Companycode = '5000';
}
else if (countrycode == 'BAH') {
Companycode = '4000';
}
else if (countrycode == 'KWT') {
Companycode = '6000';
}
$.ajax({
type: "POST",
url: "Header.aspx/Getcompanies",
data: JSON.stringify({ Countrycode: countrycode, Companycode: Companycode }),
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$("#ddlCompany").append($("<option></option>").val(value.CompanyCode).html(value.CompanyName));
});
}
});
}
BindDivision: (Bind Division method requires three Parameter 1. CompanyCode, 2. CountryCode, 3. DivisionCode)
I can able to pass only two parameters (CompanyCode, CountryCode)
But not sure how to Pass DivisionCode. (I know GetCompany Method returning three parameter and i am binding company drop down using CompanyCode and CompanyName But what about DivisionCode)Because where should I store DivisionCode field
function BindDivision() {
//var DivisionCode = Not sure how to pass
var companycode = $('#ddlCompany').val();
var countrycode = $('#ddlCountry').val();
$('#ddlDivision').empty();
$.ajax({
type: "POST",
url: "Header.aspx/GetDivision",
data: JSON.stringify({ Countrycode: countrycode, Companycode: companycode }),
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$("#ddlDivision").append($("<option></option>").val(value.DevisionCode).html(value.DevisionName));
});
}
});
}
In my AJAX method i am passing two parameter from selected drop down list and i want to pass another parameter that is DivisionCode from One WebMethod to another Webmethod.
Probly we can pass from AJAX but how can i store In ASPX (DevisionCode is not singe value it is list as you can see i am storing thoes value in List only)
Please help me
Related
I have method to add data to db on Aajax request
Here is code on back-end
public ActionResult AddingInternalAppointment(string Start, string End, string Title, DateTime Date,int id)
{
using (var ctx = new ApplicationDbContext())
{
Appointment appointmentInt = new Appointment()
{
Start_appointment = Start,
End_appointment = End,
Title = Title,
Type_of_appointment = "Internal",
Date = Date
};
ctx.Appointments.Add(appointmentInt);
ctx.SaveChanges();
return Json(new {Result = "Success", Message = "Saved Successfully"});
}
}
And here is AJAX request on front - end:
function addAppointmentInternal() {
var idofdoctor = moment($('#startAppointment').val()).toISOString();
alert(idofdoctor);
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
Start: $('#startAppointment').val(),
End: $('#endAppointment').val(),
Title: $('#title').val(),
Date: moment($('#startAppointment').val()).toISOString()
},
url: '#Url.Action("AddingInternalAppointment","Calendar")',
success: function (da) {
if (da.Result === "Success") {
$('#calendar').fullCalendar('refetchEvents');
$("#myModal2").modal();
} else {
alert('Error' + da.Message);
}
},
error: function(da) {
alert('Error');
}
});
}
When I call this function it show me this error, but I have values in Date.
How I can fix this?
Try changing parameter name Date to something else (like appointmentDate). You need to change same in ajax call.
A few things.
Create a model for the Action
public class AppointmentOptions {
public string Start { get; set;}
public string End { get; set;}
public string Title { get; set;}
public DateTime Date { get; set;}
public int Id { get; set;}
}
Update the action accordingly
[HttpPost]
public ActionResult AddingInternalAppointment([FromBody]AppointmentOptions model) {
if(ModelState.IsValid) {
string Start = model.Start;
string End = model.End;
//...
//...code removed for brevity
}
Next on the client update ajax call
function addAppointmentInternal() {
var idofdoctor = moment($('#startAppointment').val()).toISOString();
var model = {
Start: $('#startAppointment').val(),
End: $('#endAppointment').val(),
Title: $('#title').val(),
Date: moment($('#startAppointment').val()).toISOString()
};
alert(idofdoctor);
$.ajax({
type: 'Post',
dataType: 'Json',
data: JSON.stringify(model), //<-- NOTE
url: '#Url.Action("AddingInternalAppointment","Calendar")',
success: function (da) {
if (da.Result === "Success") {
$('#calendar').fullCalendar('refetchEvents');
$("#myModal2").modal();
} else {
alert('Error' + da.Message);
}
},
error: function(da) {
alert('Error');
}
});
}
I can't figure out why my action param is coming through null. I'm also not sure of how to even diagnose the issue. I can see the http request data being sent with data and stepping through the debugger shows the object as null, not sure how to see the steps in between.
Models
public class ComplexObj
{
public int Id { get; set; }
public int Test1 { get; set; }
public decimal Test2 { get; set; }
}
public class BiggerObj
{
public BiggerObj()
{
ComplexObj = new List<ComplexObj>();
}
public long OtherId { get; set; }
public string Name { get; set; }
public ICollection<ComplexObj> ComplexObjs { get; set; }
}
Action
[HttpPost]
public void TestAction(BiggerObj[] biggerObjs)
{
...// biggerObjs is null :(
}
View
function ajaxCall() {
var data = [];
var bigObj = new Object();
bigObj.OtherId = 123;
bigObj.Name = "TestName";
bigObj.ComplexObj = [];
var complexObj = new Object();
complexObj.Id = 789;
complexObj.Test1 = 123;
complexObj.Test2 = 456;
bigObj.ComplexObj.push(complexObj);
data.push(bigObj);
}
}
$.ajax({
url: SITEROOT + "myController/TestAction",
cache: false,
type: 'POST',
data: data,
complete: function() {
alert('done');
}
});
}
Solved
You must use:
JSON.stringify and declare the contentType as "application/json; charset=utf-8"
Parse the decimal value by using parseFloat() function, decimal is considered as int by default binder.
Change your Action to this:
[HttpPost]
public ActionResult TestAction(BiggerObj[] biggerObjs)
{
...// biggerObjs is null :(
}
Change your ajaxCall function to this:
//ajaxCall
function ajaxCall() {
var data = [];
var bigObj = {
OtherId : 123,
Name : "TestName",
ComplexObjs : new Array()
};
var ComplexObjs = {
Id: 789,
Test1: 123,
Test2: parseFloat(456)
// decimal types are considered an integer, you have to parse
};
bigObj.ComplexObjs.push(ComplexObjs);
data.push(bigObj);
$.ajax({
url:"/Test/TestAction",
cache: false,
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
complete: function () {
alert('done');
}
});
}
I tested, works fine.
I'm trying to post back a list of data objects (WorkOrders), in JSON format to my Webapi controller, this works amazingly well, except for the slight flaw in that the data object parameter (savemodel) is null when it hits the webapi controller.
This is a snip from the JS (slots is mock data)
var slots = [];
slots.push({ 'WorkOrder': 'XX21', 'OrderDate': '2015-10-11 00:00:00', 'Slot': '1', 'SageRef': 'HS11' });
slots.push({ 'WorkOrder': 'XX22', 'OrderDate': '2015-10-12 00:00:00', 'Slot': '2', 'SageRef': 'HS12' })
slots.push({ 'WorkOrder': 'XX23', 'OrderDate': '2015-10-13 00:00:00', 'Slot': '3', 'SageRef': 'HS13' });
console.log(JSON.stringify({ 'savemodel': slots }))
$.ajax({
type: "POST",
url: 'http://localhost:55821/api/schedule',
data: JSON.stringify({ 'savemodel': slots }),
contentType: 'application/json; charset=utf-8'
}).success(function (data) {
$scope.$apply(function () {
if (data.SaveMessage.length > 0) {
// do something
}
else {
// do something else
}
});
});
The model:
public class WorkOrderModel
{
public string WorkOrder { get; set; }
public string OrderDate { get; set; }
public string SlotNumber { get; set; }
public string SageRef { get; set; }
}
The postback method:
[HttpPost]
public IHttpActionResult UpdateWorkOrder([FromBody]List<WorkOrderModel> savemodel)
{
StringBuilder saveMessage = new StringBuilder();
foreach (WorkOrderModel model in savemodel)
{
// save the WO model object here
}
if (saveMessage.Length > 0)
{
return Ok(new { SaveMessage = "There were issues: " + saveMessage.ToString() });
}
else
{
return Ok(new { SaveMessage = "" });
}
}
Posted JSON
Null parameter in the WebApi Controller
This is driving me nuts so any help will be hugely appreciated at this stage!
Regards,
itsdanny
Sorted, it changed
data: JSON.stringify({ 'savemodel': slots}),
to
data: JSON.stringify(slots),
function myItemsViewModel(ItemID, GroupID, ItemName, Quantity) {
this.ItemID = ItemID;
this.GroupID = GroupID;
this.ItemName = ItemName;
this.Quantity = Quantity;
}
And i have below code for posting to the controller
var CreateRecord = function () {
var Name = $.trim($("#divCreate").find("#txtName").val());
var Department = $.trim($("#divCreate").find("#txtDepartment").val());
var ItemsList = [];
$('#myDynamicTable').find('tr').each(function () {
var row = $(this);
var itemName = $.trim(row.find(".itemName input").val());
var itemQty = $.trim(row.find(".itemQty input").val());
var myItems = new myItemsViewModel("", "", itemName, itemQty);
ItemsList.push(myItems);
});
var obj = new myRecordEntryViewModel("", Name, Department, ItemsList);
var viewmodel = JSON.stringify(obj);
$.ajax({
type: 'POST',
cache: false,
dataType: 'html',
data: viewmodel,
headers: GetRequestVerificationToken(),
contentType: 'application/json; charset=utf-8',
url: '/' + virtualDirectory + '/RecordEntry/Save',
success: function (data) {
$("#divMaster").html(data);
return false;
},
error: function (msg) {
alert("Error Submitting Record Request!");
}
});
}
At the line var viewmodel = JSON.stringify(obj);, viewmodel has all the values that i want in my ItemsList array variable.
Problem is my ItemsList array is coming as null in the controller. Name and Department are coming through with the correct passed values.
Below is my controller code.
Class
public class myRecordEntryViewModel
{
public long ID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public string[] ItemsList { get; set; }
}
Save action
[ActionName("Save")]
[NoCache]
public ActionResult Save(myRecordEntryViewModel viewModel)
{
//here viewModel.ItemsList is null, what could i be missing
if (this.SaveEntry(viewModel.Name,viewModel.Department,viewModel.ItemsList))
{
}
return this.View();
}
I'm wondering why viewModel.ItemsList is coming as null in controller yet it has values during the post from jQuery.
You should create a class for the Item in Item List (In C#)
public class Item {
public string ItemName { get; set; }
public int Quantity { get; set; }
}
And then change the viewmodel class
public class myRecordEntryViewModel
{
public long ID { get; set; }
public string Name { get; set; }
public string Department { get; set; }
//public string[] ItemsList { get; set; }
public List<Item> ItemsList {get ; set;}
}
The controller can not map the Item List from your request into model because one is a list of string and other is a list of object.
There are several problems in your codes...
1) ItemList in your class and your javascript code are not same - The frist one is an array of strings, and the second is an array of objects
2) In your action method, you should change parameter type like the following:
public ActionResult Save(string viewModel)
3) In the body of your action method, you should deserialize the json string (viewModel) and make the model object from it. The following is an example...
https://stackoverflow.com/a/17741421/1814343
Try the below code and see if your model gets the values.
Let me know if you face any problems, because I've already implemented this in one of my projects
var CreateRecord = function () {
var Name = $.trim($("#divCreate").find("#txtName").val());
var Department = $.trim($("#divCreate").find("#txtDepartment").val());
var model="";
var ItemsList = [];
$('#myDynamicTable').find('tr').each(function () {
var row = $(this);
var itemName = $.trim(row.find(".itemName input").val());
var itemQty = $.trim(row.find(".itemQty input").val());
var myItems = new myItemsViewModel("", "", itemName, itemQty);
ItemsList.push(myItems);
});
model = ['Name' : Name , 'Department' : Department , 'ItemsList' :ItemsList];
$.ajax({
type: 'POST',
cache: false,
dataType: 'html',
data: JSON.stringify(model),
headers: GetRequestVerificationToken(),
contentType: 'application/json; charset=utf-8',
url: '/' + virtualDirectory + '/RecordEntry/Save',
success: function (data) {
$("#divMaster").html(data);
HideLoader();
return false;
},
error: function (msg) {
alert("Error Submitting Record Request!");
HideLoader();
}
});
}
I have an .aspx page that we are loading UserControls into dynamically at runtime. Each user control has some sort of textbox or combo or some other control. This all works fine. when we go to read the values out of the controls when the user presses search, we cannot do this directlly from C# code behind because the page does not know they are there. my solution is to read the values with JQuery and make an ajax call where I can set the values in a session variable for use when the user gets to the next page. I am having trouble with the JSon specifically.
I keep getting the error:
{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":"
I find all the controls using .each and get the values for the JSon call:
function SaveFields() {
var data = [];
//get Search field criteria
$('[id^=Search_ucField_]').each(function (index, value) {
var field = $(this);
var id = $(this).attr('id').split("_")[2];
var fieldValue = $(this).val();
if (field.is('input')) {
var item = {};
item['FieldID'] = id;
item['Criteria'] = fieldValue;
item['IsActive'] = 1;
item['FieldCategoryID'] = '1';
item['ControlPath'] = '~/Controls/Search/TextBox.aspx';
item['CategoryID'] = 1;
data.push(item);
}
});
$.ajax({
url: '/Ajax/Ajax.aspx/DoSearch',
type: 'POST',
data: JSON.stringify(data),
datatype: 'json',
contentType: 'application/json',
success: function (msg) {
console.log(msg);
},
error: function (xhr, textStatus, errorThrown) {
alert('Error! Status = ' + xhr.status);
}
});
}
Here is the object I am trying to deserialize into:
[DataContract]
public class SearchFields
{
[DataMember]
public List<SearchField> Field { get; set; }
}
[DataContract]
public class SearchField
{
[DataMember]
public string FieldID { get; set; }
[DataMember]
public bool IsActive { get; set; }
[DataMember]
public string Criteria { get; set; }
[DataMember]
public int FieldCategoryID { get; set; }
[DataMember]
public string ControlPath { get; set; }
}
Here is the WebMethod
[WebMethod]
public static string DoSearch(string Fields)
{
var sf = new SearchFields();
sf = JsonConvert.DeserializeObject<SearchFields>(Fields);
//save into session variable
SVars.NewUISearch.LastSearchFields = sf;
string x;
x = "until this works, this is a static response";
return x;
}
finally, here is a sample of the JSon that is being sent:
[{"FieldID":"52","getCriteria":"Bobs your uncle","IsActive":1,"FieldCategoryID":"1","ControlPath":"~/Controls/Search/TextBox.aspx"}]
Where am I going wrong here? Thanks in advance!
I couldn't get $('form').serialize() to work so this is what I did. Make sure the properties you define in model represent the properties in your model and are strongly typed.
var model = {
MyString: $("#MyString").val(),
MyNumber: $("#MyNumber").val(),
IsCheck: $("CHK").val()
};
$.ajax({
type: "POST",
url: "/Testing/Index",
contentType: "application/json",
data: JSON.stringify(model),
dataType: "json",
success: function (data) {
// Good stuff
},
error: function (data) {
// Bad stuff
}
})