Pass data in a .getJSON. Possible? How? - c#

I'm doing an app and I got a select where the user can choose different Teams. Each team contains a couple of patients. I save the chosen team with the data-bind selectedOptions and stores the option to an observable called 'selectedTeam'.
I'm receiving a list of patients by calling
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
self.searchPatients();
Back at my APIController I got a method that asks the DB for patients. This calls takes different arguments, one of them being what team to search from.
My question is how to pass the observable 'selectedTeam' to my APIController, convert it to a string to pass it to the DB call.
thx

You can pass the data as a second argument of getJSON function :
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", { param1: 'anyvalue' }, function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
self.searchPatients();

Assuming the server method looks like as follow :
[HttpGet]
public Object GetPatients(String team)
{
// return the patients
}
You should use this JavaScript :
self.searchPatients = function () {
$.getJSON("/api/API/GetPatients", { team: self.selectedTeam() }, function (data) {
ko.mapping.fromJS(data, {}, self.patients);
});
};
Because self.selectedTeam is an observable you can't send it to the server.What you want to send is its value. That's why you need to 'call' the observable.
self.selectedTeam() // returns the value of the observable.
I hope it helps.

To pass data to controller you can use jquery ajax call as follows,
$.ajax({
type: "POST",
url: "api/API/GetPatients",
data: JSON.stringify(yourObject), // data to be passed to controller
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// your success call
},
error: function () {
alert("Unable to Save.");
}
});

Related

Trouble sending JSON data to another action in asp.net MVC controller

I have this controller action:
[HttpPost]
public ActionResult OrderData(Order order)
{
var result = new { redirectToUrl = Url.Action("SeatSelection", "Orders", new { id = order.ScreeningId }), order };
return Json(result);
}
and I'm trying to pass the order object to another action:
public ActionResult SeatSelection(int id, Order order)
{
var screeningInDb = _context.Screenings.Include(s => s.Seats).Single(s => s.Id == order.ScreeningId);
var viewModel = new SeatSelectionViewModel
{
Seats = screeningInDb.Seats,
NumberOfTicketsOrdered = order.NumberOfTicketsOrdered
};
return View("SeatSelection", viewModel);
}
The problem is - the only parameter I'm receiving in SeatSelection Action is the id parameter, although the order object in OrderData Action is valid. I'm pretty sure the problem is within the way I'm trying to pass the order object, maybe something with the syntax?
Here is the way I'm posting my form data to the OrderData Action:
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(orderData),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
Bottom line - What I'm eventually trying to do is to pass the form to a Controller Action where the data will be processed, and then pass the new data to "SeatSelection" view. I had trouble doing this as my post method sends JSON data, so if there is a better way to do what I'm trying to do, I would be happy to learn!
Your model doesn't match SeatSelection parameter signature.
Try:
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: `{"order": ${JSON.stringify(orderData)}}`,
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
or (this one just creates a javascript object, which has the two signature properties in):
const sendObj = { id: 0, order: orderData };
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(sendObj),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
you can't use
window.location.href = ...
because in this case browser always calls a GET method that can only keep data in a query string with primitives parameters and it doesn't convert Order to a qusery string parameters. This is why you can get only id.
in your case it would be much easier to redirect directly in the action
public ActionResult OrderData(Order order)
{
return RedirectToAction( ( "SeatSelection", "Orders", new { id = order.ScreeningId }), order });
}
or when it is the same controller I usually do this
public ActionResult OrderData(Order order)
{
return SeatSelection (order.ScreeningId, order };
}
but since you are using ajax it will redirect, but will not update your view. For ajax you need a partial view that should be updated on success. So instead of ajax you can only submit form using button. In this case everything will be working ok.
Another way you can use ajax is you can try to split the order in properties and create a query string.

Ajax Post not finding method in page model

I have the following method inside my page model which is called Order
public async Task<IActionResult> OnPostAddRecord(string recordId)
{
return new JsonResult("Hello");
}
My Ajax code to call said method:
$('#RecordList').change(function () {
var formData = {
recordId: $("#RecordList").val(),
};
$.ajax({
type: 'POST',
data: formData,
url: '#Url.Page("order", "addrecord")',
success: function (result) {
alert(result)
},
error: function (result) { }
});
});
Yet when it's fired it returns StatusCode 400, however, I have another Ajax method on the same page that works successfully, the difference is that one is a GET whereas this is a POST.
I really can't see what the problem is here.
You need to include the request verification token in your FormData: https://www.mikesdotnetting.com/article/336/ajax-posts-in-razor-pages-and-http-400-errors

Array inside object for jQuery getJSON not populated

I have a rather peculiar problem when trying to use the jQuery getJSON function.
I try to send my parameters by making an object like so:
var args = {
from: "",
to: "",
customerId: "52"
articles: ['12312', '21521']
};
Then call the getJSON function:
$.getJSON('/Statistics/TimeGraph', args, function (response) {
//Fill graph.
});
This is where the problem starts. I recieve the request on the controller, but articles is not populated (the other parameters are).
Controller action:
public JsonResult TimeGraph(DateTime? from, DateTime? to, int? customerId, string[] articles)
{
return Json("", JsonRequestBehavior.AllowGet);
}
Is it not possible to send an array inside an object like this? Or is there something I'm missing?
You need to set traditional parameter to true, otherwise it will not work correctly.
$.getJSON('/Statistics/TimeGraph', $.param(args,true), function (response) {
//Fill graph.
});
or simple ajax call
$.ajax({
type: "GET",
url: "/Statistics/TimeGraph",
data: args,
success: function(response){
//Fill graph.
},
dataType: "json",
traditional: true
});

Auto Complete in Razor MVC.NET [duplicate]

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

Ajax post doesn't populate data to a dropdown select list

What I missing about posting to ActionMethods to pull data here ?
I need to do a simple javascript/jquery call to an ActionMethod that will populatel my drop down menu with data from my Json object of type IQueryable ( or List ).
So I tried two options:
function populateuUsers(id) {
$.post("/User/GetUsersJson/", { id: id }, function (data) {
if ($.isEmptyObject(data)) {
alert("Empty");
}
$.each(data, function (item) {
alert(item);
$("#user-list").append(
$("<option></option>").text(data[item].FullName).val(data[item].Id)
);
});
}, "json");
}
I get an error that "data is undefined"
Then I tried:
function populateUsers(id) {
$.ajax({
type: 'post',
datatype: 'json',
url: "/User/GetUsersJson/" + id,
success: function (data) {
alert(data);
$.each(data, function (item) {
alert(item);
$("#users-list").append(
$("<option></option>").text(data[item].FullName).val(data[item].Id));
});
},
error:function()
{
alert(data);
}
});
}
Doesn't work either.
Something to note...I set break points and did verify that data in GetUsersJson Action method User controller gets properly populated and returned to the javascript function.
Why is it not working then ? Why is "data undefined" and it acts like there nothing returned ?
Thank you in advance.
Inside the anonymous function that you're passing to $.each, data is not defined. Instead you should pass two variables to that function. Something like:
$.each(data, function (key, item) {
alert(item);
$("#users-list").append(
$("<option></option>").text(item.FullName).val(item.Id));
});
http://api.jquery.com/jQuery.each/

Categories