How to pass parameters to GET WebApi endpoint via AJAX call? - ajax

I have a GET WebApi endpoint that's part of my MVC application that I want to use to process some data I send to it, and am to accomplish the sending of this data via a jQuery AJAX call.
However, I'm having some trouble passing in the parameters I want, via the AJAX call. Currently I'm compiling all the parameters I need into one object, using JSON.stringify() to convert the parameters into a string, and sending along that as data.
Is there something else I'm missing here? I'm able to pass these parameters along just fine if I'm doing a POST, but I'd like to avoid that since my endpoint is not responsible for inserting or updating any data.
Below is the code I'm using for both WebApi endpoint and AJAX call.
WebApi endpoint:
Method:
[HttpGet]
[Route("api/services/getservices")]
public IHttpActionResult GetServices(ServiceViewModel vm)
{
return Ok(Request);
}
Classes:
public class ServiceViewModel
{
public ServiceModel service { get; set; }
}
public class ServiceModel
{
public string thing1 { get; set; }
public string thing2 { get; set; }
public string thing3 { get; set; }
public string thing4 { get; set; }
}
AJAX:
var thing1 = $("#thing1").find(":selected").attr("program-id");
var thing2 = $("#thing2").val();
var thing3 = $("#thing3").val();
var thing4 = $("#thing4").val();
var obj = {
thing1: thing1,
thing2: thing2,
thing3: thing3,
thing4: thing4
};
obj = { "service": obj };
$.ajax({
contentType: "application/json",
url: "/api/services/getservices",
type: "GET",
data: JSON.stringify(obj),
cache: false,
success: function (data) {
console.log(data);
console.log("got here");
serviceTable(data);
},
error: function () {
servicEngineService.getProgramServices(programId, generateServiceTable, getProgramServicesFailure);
}
});

You should use:
data: {
thing1: thing1,
thing2: thing2,
thing3: thing3,
thing4: thing4
};
They will be passed in the query string, so take care, it shouldn't be too long.
As Nkosi said, GET requests don't have a body. If it gets too long for the query string you should use a POST, even if your back-end won't modify data.

Related

I can't send data to a list of objects with ajax

net core 6.0 code class :
public class plansdto{
public short status { get; set; }
public List<PlanItemDto> items { get; set; }
}
public class PlanItemDto{
public short currency
}
Ajax code :
<script>
$("#button").click(function() {
let plandto= {};
plandto.status = $("input[name='status']").val();
plandto.items = $("input[currency='currency']".val();
});
$.ajax({
traditional: true,
type: "post",
url: "/CommissionPlan/CreateAccountsCommission",
data: plandto,
success: function(func) {
let result = JQuery.parseJSON(func);
alert("ok");
}
});
</script>
not working!
status data sent but items data isnot sent.
plase help me. Ajax Object inside List send data

Adding via ajax one to one related data .net Core

I have 2 tables, one is a one to one or one to zero relationship:
public class ComponentText
{
[Key]
public int ComponentTextId { get; set; }
public string ComponentContent { get; set; }
public ComponentTextSection ComponentTextSection { get; set; }
}
public class ComponentTextSection
{
[Key]
public int ComponentTextId { get; set; }
public string SectionTitle { get; set; }
public ComponentText ComponentText { get; set; }
}
I can add row fine using usual .net core posting using a form, here is code which does this:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var newComponentText = new ComponentText();
if (await TryUpdateModelAsync<ComponentText>(
newComponentText,
"ComponentText",
i => i.ComponentTextSection, i => i.ComponentContent))
{
_context.ComponentText.Add(newComponentText);
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
I need to update though via ajax, but I am having issues updating the SectionTitle using this current way. It adds the data to the ComponentText table fine but not the ComponentTextSection table. Here is my ajax code:
function saveWindow() {
var ComponentText = { "ComponentText.ComponentTextSection.SectionTitle": $("#ComponentText_ComponentTextSection_SectionTitle").val(),
"ComponentTextId": $("#ComponentText_ComponentTextId").val(),
"ComponentContent": $("#ComponentText_ComponentContent").val()};
$.ajax({
type: 'PUT',
contentType: 'application/json; charset=utf-8',
headers: {
'RequestVerificationToken': '#AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'
},
data: JSON.stringify(ComponentText),
url: '#Url.Page("Edit", "demo4")',
success: function (result) {
closeWindow();
}
});
}
It must be to do with ComponentText.ComponentTextSection.SectionTitle but I have been trying lots of things to get this to work but failing. Does anyone know how to pass a one to one related data via ajax?
Thanks
For the one-to-one model, if you want to use ajax to transfer the complex nested model to the page, you need to create the same as the ComponentText model structure in saveWindow function of ComponentText variable.
<script>
function saveWindow() {
var ComponentText = {
"ComponentTextSection":
{
"SectionTitle": $("#ComponentText_ComponentTextSection_SectionTitle").val(),
},
"ComponentTextId": 1,
"ComponentContent": $("#ComponentText_ComponentContent").val()
};
$.ajax({
type: 'PUT',
contentType: 'application/json; charset=utf-8',
headers: {
'RequestVerificationToken':
'#AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'
},
data: JSON.stringify(ComponentText),
url: '#Url.Page("Edit", "demo4")',
success: function (result) {
closeWindow();
}
});
}
</script>
Here is the test result:

How to pass dictionary item from client side (Ajax) to server side (MVC API)

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");
});

Empty data send by json

For unknown reason for me data received by my function in controller is always null.
My data is translated into json properly. Data is send but not received (sending ends with success).
Here You can see my Ajax function
$.ajax({
url: "/Devices/Read",
contentType: "text",
type: "POST",
datatype: "json",
data: ko.toJSON(self),
error: function (xmlHttpRequest, errorText, thrownError) {
console.log("error")
},
success: function (data) {
if (data != null) {
console.log("success");
}
}
});
here my function in controller:
[HttpPost]
public ActionResult Read(string data)
{
return Json(new Object());
}
I tried:
changing parameter type to: Object, String
changing contentType to : text, application/json; charset=utf-8
Still no efects. Can anyone suggest me where should I search for mistake?
UPDATE:
After changing method declaration to:
public ActionResult Read(object[] data, string DeviceUser, string DeviceId, string number)
Last three strings are OK but first object consist of proper number of elements but they are null.
in JS they are alements in array of classes
structure of my JS objects:
var Eq = function (name, price) {
var self = this;
self.DeviceSerialNumber = ko.observable();
self.Batch = ko.observable();
};
var ViewModel = function () {
var self = this;
self.data = ko.observableArray([]);
self.DeviceUser = ko.observable();
self.DeviceId = ko.observable();
self.number = ko.observable(1);
};
In your controller action, why do you:
return RedirectToAction("Index");
I think you may want to:
return Json(data);
If you are writing an HTTP Post method, then the redirect to action does not really make sense, because you are posting data, not requesting a page.
You could do something like this:
[HttpPost]
public ActionResult Read(string Data)
{
return Json(Data);
}
OK problem was in setting proper parameter type in method.
TO solve my problem I need to modify method declaration to:
public ActionResult Read(ViewModel m)
and add ViewModel like this:
public class ViewModel
{
public List<InnerClass> data { get; set; }
public string DeviceUser {get;set;}
public string DeviceId {get;set;}
public int number {get;set;}
}
public class InnerClass
{
public string DeviceSerialNumber { get; set; }
public string Batch { get; set; }
}
now all data is received.
Thanks You all for help and suggestions. I will give you all +1 :)

serialize List<SelectListItem> from View to Controller in MVC 3

I'm having issues passing my list object to my controller - using an ajax post.
in the view I have this:
try {
var id = schedule.value;
var data2 = #Html.Raw(Json.Encode(Model.SavedScheduleList));
var url = '#Url.Action("SetActiveSchedule", "Frame")';
$.post(url, { savedScheduleList: data2, signScheduleDataId: id }, function (data) {
});
}
catch (err)
{
alert(err);
}
My Controller looks like this:
[HttpPost]
public ActionResult SetActiveSchedule(List<SelectListItem> savedScheduleList, int signScheduleDataId)
{
try
{
return Json(null);
}
catch (Exception ex)
{
throw;
}
}
So when my Action is executed, my savedScheduleList contains a list object with 7 objects (which is the correct number of items I'm sending through. However each item seems to be "blank". ie, of the SelectListItem class, these are the property values for each item: Selected = false, Text = null, Value = null.
The Model class (which has been strongly typed to this view) is:
public class ScheduleModel
{
private SignSchedule activeSignSchedule = new SignSchedule();
private List<SelectListItem> savedSignScheduleList = new List<SelectListItem>();
public int SignDataId { get; set; }
public ScheduleFrameList ListFrames { get; set; }
public DateTime Start { get; set; }
public LogMessage LogMessage { get; set; }
public bool CommsLogVisible { get; set; }
public SignSchedule SignScheduleToMakeActive { get; set; }
public int ActiveSignScheduleId { get; set; }
//public List<SignSchedule> SavedSignScheduleList { get { return savedSignScheduleList; } }
public List<SelectListItem> SavedScheduleList { get { return savedSignScheduleList; } }
}
Examining data2 before the post, shows the correct data in Json format and examining the Request property within the Action I can see the correct values in the Form.AllKeys property as well as the Params property but it doesn't seem to correctly resolve it back to my parameter object of the Controller Action.
Is it possible what I'm trying to do?
Thanks
EDIT
Here's a string representation of data2 variable:
var data2 = [{"Selected":false,"Text":"9","Value":"2589"},false,"Text":"afsdfs","Value":"2585"},false,"Text":"sdfas","Value":"2588"}....]
I'm just showing 3 items here but there is in fact 7 as expected.
The easiest way to send complex objects and lists is to use a JSON request, like this:
var id = schedule.value;
var data2 = #Html.Raw(Json.Encode(Model.SavedScheduleList));
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ savedScheduleList: data2, signScheduleDataId: id }),
traditional: true,
success: function(result) {
// TODO: do something with the results
}
});
Note that the JSON.stringify function is natively built into modern browsers. But if you need to support legacy browsers you could include the json2.js script into your page.

Resources