Let say that I do have the following url:
"/api/requests/cbd?[{"requestid":"fd45001b-339f-ac28-e053-a24c07d4e3fb"},{"requestid":"fd45001b-329f-ac28-e053-a24c07d4e3fb"},{"requestid":"fd45001b-319f-ac28-e053-a24c07d4e3fb"}]"
How to bind the parameters - array with asp.net web api 2 action?
This I have tried but it is not working.
[HttpGet]
[Route("api/requests/cbd")]
public IHttpActionResult CanBeDeleted([FromUri] string[] requestIds )
{
return Ok(result);
}
You are passing an array of objects so viable option would be create a class like:
public class Ids
{
public Guid requestid {get;set;}
}
and use it like:
[HttpGet]
[Route("api/requests/cbd")]
public IHttpActionResult CanBeDeleted([FromUri] IEnumerable<Ids> requestIds )
{
return Ok(result);
}
or send only ids, without property name.
you can keep the action in the web api like that and just change the http call into:
"/api/requests/cbd?requestid=1&requestid=2&requestid=3"
if you need the http call to be as you presented it, you can take Kamo's approach and create objects for your parameter collection.
You can use this in your Controller:
public IHttpActionResult CanBeDeleted(JObject request)
{
Dictionary<string, object> myCollection = JsonConvert.DeserializeObject<Dictionary<string, object>>(request["NameOfYourParam"].ToString());
return OK();
}
Related
I'm currently writing a website using ASP.NET Core, HTML, and Javascript. Currently, I have a page of the website that loads a chart of Equipment and stats on them. Below the chart is an area where the user can select specific equipment whose details they want to view. This info is then sent to the controller, which returns info back to the View about them.
However, while I know that the AJAX call does go to the controller when I look at it with breakpoints, and I know the value of my selected equipment is corrected, it always returns a "null" string value to the controller and I don't know why.
I've attempted a couple of different ways of writing it according to code I've seen on SO. My code was similar (structurally speaking) to the code on this page. I attempted the solution, which is the code I have now, but it didn't seem to change anything.
Here is my current javascript code:
function filterInterventions() {
var equipment = $(".equipmentCheckboxes:checkbox:checked").map(function () {
return this.value;
}).get();
$("#IntrvTable tbody tr").remove();
$.ajax({
type: "GET",
data: equipment,
cache: false,
//url: "GiveData?jsonString=",
url: '#Url.Action("GiveData")',
success: function (data) {
if (data) {
alert("success");
var parent = $("#parent");
parent.empty();
parent.append(data);
}
}
});
}
And here is my controller code:
public ActionResult GiveData(string jsonString){
//do stuff....
return View("RawData", myModel);
}
When I step through it in the browser and on my IDE, I know that the equipment in the actual javascript is correct. For example, if I selected equipment 'AA' and 'BB' to look at, I know I'm sending in ["AA/", "BB/"]. But I just cannot get the "jsonString" in the controller action to be non-null.
I thought it might be because I'm sending in an array, but the things I've found online about turning on traditional have also not helped.
I would love any help. Thanks.
I believe what you'd be looking for would be:
data: { 'jsonString': JSON.stringify(equipment) }
Normally though JSON would be used for an object rather than an array of strings, and the method signature would reflect the object definition of the data being passed as a POCO class. If you just want an array then something like this should work:
data: { 'equipment' : equipment }
with the controller action signature:
public ActionResult GiveData(string[] equipment)
Edit: JSON / POCO example
For a typical JSON example let's say you have a view model representing editing a new or existing order. This may have an Order ID, an order date, a customer ID, delivery address details, and a list of order lines. (product ID, quantity) On the client side you would construct a JS object view model for the data and then compose that to JSON to look something like:
{
"order": {
"orderId": 1234,
"orderDate": "2019-07-21",
"customerId": 216,
"deliveryAddress": {
"street": "216 Cuckoo Crescent"
"city": "Sydney"
}
"orderLines": {
{ "productId": 22, "quantity":1 },
{ "productId": 15, "quantity":3 }
}
}
}
where the Ajax call data component would look like:
data: { 'order': orderJson }
If the order data was just a Javascript object then you would use JSON.stringify(order) to pass the JSON representation.
In your server you would define these view models:
[Serializable]
public class OrderViewModel
{
public int? OrderId { get; set; }
public DateTime OrderDate { get; set; }
public int CustomerId { get; set; }
public AddressViewModel Address { get; set;}
public ICollection<OrderLineViewModel> OrderLines { get; set; } = new List<OrderLineViewModel>();
}
[Serializable]
public class AddressViewModel
{
public string Street { get; set; }
public string City { get; set; }
// ...
}
[Serializable]
public class OrderLineViewModel
{
public int ProductId { get; set; }
public int Quantity { get; set; }
}
In your method signature you would like:
public ActionResult CreateOrder(OrderViewModel order)
ASP.Net will accept the JSON object and your code can work with the POCO classes automatically. This is pulling from memory, and might require/involve a library like JSON.Net with some attribute goodness or extra steps so there may be some tweaking and config needed, especially to accommodate Pascal vs. Camel casing conventions between the JS and C# code. The onus though is on the developers to keep the POCO definitions and JS objects in-sync, and ensure the data types are compatible.
It is now quiet a default behavior - to map raw data to plain string.
Instead of mapping to string it is usually a better way - to map the JSON to the corresponding class type.
If raw data is the goal - here might be something you are looking for.
Okay, curerntly I am displaying some data on a html page. I have used jquery ajax call which get the data from the specific url on spring MVC application and return data and then use javascript to display data in the table.
#RequestMapping(value = "/students", method = RequestMethod.GET)
#ResponseBody
#JsonView(Views.PublicView.class)
public ArrayList<Student> getAdminsList(HttpSession session) {
//return data
}
Now, my question is, I get data as I required via ajax, but I do get data displayed in the browser if I just go through url: www.example.com/students - will display JSON data.
Is there anyway to avoid display this data not in browser but only in ajax call?
Anyway, I just found the answer for this after lots of googling and I thought sharing it would be good thing. So, basically what is the logic for this restriction is that, whenever a call is made from ajax a special header named X-Requested-With with a value of XMLHttpRequest is attached to the request. the only thing I have to do is check this parameter on my controller.
#RequestMapping(value = "/accounts", method = RequestMethod.GET)
#JsonView(View.Accounts.class)
public List<Account> getAccounts() throws JsonProcessingException {
if(!"XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
log.info("Request is from browser.");
return null;
}
List<Account> accounts = accountService.findAccounts();
return accounts;
}
you can read the full article on this blog. http://www.gmarwaha.com/blog/2009/06/27/is-it-an-ajax-request-or-a-normal-request/
Maybe feels like being a problem[#JsonView(Views.PublicView.class)]. You check PublicView.class
Read to description. link : enter link description here
#RequestMapping(value = "/accounts", method = RequestMethod.GET)
#JsonView(View.Accounts.class)
public List<Account> getAccounts() throws JsonProcessingException {
List<Account> accounts = accountService.findAccounts();
return accounts;
}
What is the best way to create Kendo UI grid using angular and web api (for backend)? I am use MVC structure.
My model looks like:
public class Category
{
[Key]
public int CategoryID { get; set; }
[Required]
public string CategoryName { get; set; }
}
In web api controller i have following methods:
public IEnumerable<Category> GetCategories() {}
public HttpResponseMessage PostCategory(Category category) {}
public HttpResponseMessage PutCategory( Category category) {}
public HttpResponseMessage DeleteCategory(Category category) {}
Now, I wish to implement kendo ui grid using angular. How can I do that?
I am read kendo ui demos: http://demos.telerik.com/kendo-ui/grid/angular and documentation but I don't understand how can implement it. Thanks.
I have a mostly working example attached to one of my questions here
AngularJS kendo grid binding to angular service webapi - sorts always null when parsing with [fromuri]
if you attach the service url directly to the dataSource.transport instead of using a service like I did you should be good to go....
Just take out my read:xxxxx section and replace with
read: {
url: "YourWEBAPIURL",
dataType: "json"
}
I am having trouble serializing my model using #Html.Raw in javascript. I basically want to serialise the model so I can pass it through a callback method on the client and then de-serialise it on the server.
[Serializable]
public class AdvanceSearch
{
public string Name{ get; set; }
public DateTime? Date { get; set; }
}
And in the javascript
var now = #Html.Raw(Json.Encode(Model));
alert(now.Name);
But the alert always comes back as null which therefore means it hasn't serialised. Am I missing anything?
Cheers
By using the Newtonsoft json serializer/deserializer this can be achieved. To serialize your model use as below.
Name space: Newtonsoft.Json;
var now = JsonConvert.SerializeObject( Model );
To deserialize,
ViewModel vm = JsonConvert.DeserializeObject<ViewModel>( obj );
Here ViewModel is your view model. Hope it helps!
I am using MVC.
I have a view model which contains a Business object.
I need to post this Business Object back to a controller action using AJAX.
For now, I am using Url.Action function to create my request Url for AJAX and pass the Business Object id as a request parameter to the action. I then have to retrieve the object from the database to use it.
Is there a way (using Json) to pass this object as an Object? The object is shown below
public class BusinessObject : BaseBusinessObject
{
public virtual string Id { get; set; }
public virtual IDictionary Data { get; set; }
public virtual IDictionary Collections { get; set; }
}
The controller action should ideally have a deifinition like ...
public ActionResult DOThis(BusinessObject bo) {}
What you are looking for is FORM Binding, there are lot of resources available, This link gives you some insight.
You should use the JsonResult for going from the server to the client. http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=399#start
The DefaultModelBinder will take care of the binding to the server. There is also a section in this page talking about calling from JQuery to the server and getting back the JsonResult.
Hope this helps!