How can I send a date using a AXIOS Get? - javascript

I need to send a date like
2007/08/01 00:00
as one of the values in my AXIOS GET
https://restapi.azurewebsites.net/api/PublicationReport/" +
dbid +
"/" +
sortDate
As you can tell it plays havoc with the Web API controller
<Route("api/PublicationReport/{dbid}/{sortDate}")>
The controller thinks that every "/" is a new parameter.
Is there a special format that must be used or do I need to send it as a json object?
I went with
params: {
dbid: dbid,
sortDate: sortDate
},
on the client side and below for the server side
Public Function GetValues(dbid As Integer, sortDate As String) As String

You can just create an object like this:
public class SomeQuery
{
public string SomeParameter { get; set; }
public int? SomeParameter2 { get; set; }
}
And then in controller just make something like that:
[HttpGet]
public IActionResult FindSomething([FromQuery] SomeQuery query)
{
// Your implementation goes here..
//then you can access query value using HttpContext.Request.Query
}
or using method params
[HttpGet]
public IActionResult FindSomething(string value1, string value2)

Related

How To Send Request To C# Method And Get Its Parameters by Jquery

Is there any way to call an API to know its required parameters?
for example, if there is a controller has a method takes a name and date as a parameters
[HttpPost]
public string testUrl(string name,string date)
{
return "success";
}
now what I am trying to do is to make a dynamic form take an API URL and generate all required inputs so I have to find some way to call the URL and return the required parameters.
The quick and dirty way would be to just hard code it:
[HttpPost]
public string testUrl(string name,string date)
{
return "success";
}
public APISchema TestUrlSchema(){
return new APISchema() {
Parameters = new List<Parameter>(){
new Parameter(){ Name = "name", Type = "String" },
new Parameter(){ Name = "date", Type = "String" }
}
};
}
public class APISchema {
public List<Parameter> Parameters {get;set;}
}
public class Parameter {
public String Name {get;set;}
public String Type {get;set;}
}
You could use Reflection to auto-generate this if you want to do it for a large number of actions.
As comments have mentioned, there are libraries Swagger which will do this for you.

javascript call MVC Controller parameter always null when object field is private

I use javascript to call controller to process a function.
The parameter value (name in summary) is null when the field is set to private.
It works when the field is set to public.
Is set to public the only way? or there is a better way to do it?
thanks in advance.
My object
[DataContract]
public class Summary
{
[DataMember]
public int id { private set; get; }
[DataMember]
public string name { private set; get; }
public summary() {}
public summary(int id, string name)
{
id = id;
name = name;
}
}
MVC Controller
public ActionResult SetSummary(Summary summary)
{
string anme = summary.name; **<-- null if private**
...
}
Javascript
$http.post("MyController/SetSummary", JSON.stringify({
summary: mySummaryObject}))
.success(function (data, status, headers, config) {
....
}
yup, it should be public because defaultmodelbinder Maps a browser request to a data object. This class provides a concrete implementation of a model binder.
The DefaultModelBinder class maps the following types of objects to a browser request:
Primitive types, such as String , Double, Decimal , or DateTime objects.
Model classes, such as Person, Address, or Product.
Collections, such as ICollection, IList, or IDictionary.
Source: https://msdn.microsoft.com/en-us/library/system.web.mvc.defaultmodelbinder(v=vs.118).aspx
Hope it was useful kindly let me know your thoughts or feedbacks
Thanks
Karthik

AngularJs post query string to c# controller

I have an AngularJS app that has to post data to a 3rd party URL. To get around the CORS browser issue, I am posting the data to my .net controller which will then post it to the 3rd party URL. In my javascript file, I've built the query string I want to pass to the 3rd party URL. Here is my code that posts to my .net controller:
var parms = "name=john&phone=1234567890&sex=male";
return $http({
url: '/UserForm/PostData/',
method: "POST",
data: parms
});
My c# controller:
[HttpPost]
public string PostData(String parms)
{
return "";
}
the parms variable in PostData is null. What do I need to do to pass my querystring string to my controller?
Can you try this? First - why don't you just define all parameters inside the controller post request definition? Second - I guess you have an error in your URL, you don't need the slash after "/UserForm/PostData" (If you don't use some custom routing in your MVC of course)
$http.post("/UserForm/PostData", { name: "john", phone: "1234567890", sex: "male" }).then(blahblahal....;
+
[HttpPost]
public string PostData(String name, String phone, String sex)
{
return "";
}
If this is for a WebApi controller, instead of trying to read parms as a parameter passed to the action, use ReadAsString to read the posted data. In your example the result should be the same value in your parms variable.
[HttpPost]
public IHttpActionResult PostData()
{
var parms = Request.Content.ReadAsStringAsync().Result;
// Submit parms to third-party api.
return Ok();
}
This task is more appropriate for WebApi, but if you need to use an MVC controller, you can read what was posted by reading Request.InputStream:
public ActionResult PostData()
{
string parms;
using (var sr = new System.IO.StreamReader(Request.InputStream))
{
parms = sr.ReadToEnd();
}
// Submit parms to third-party api.
return new EmptyResult();
}
You can try this.
[HttpPost]
public string PostData(System.Net.Http.Formatting.FormDataCollection form)
{
string name=form.get("name");
string phone=form.get("phone");
string sex=form.get("sex");
}
Or else you can try this solution too, you just need to add couple of lines.
public class PersonData
{
public string name { get; set; }
public string phone { get; set; }
public string sex { get; set; }
}
[HttpPost]
public string PostData([FromBody]PersonData form)
{
string name=form.name;
string phone=form.phone
string sex=form.sex;
}

ASP.NET MVC - How to "reverse" model binding to convert a C# model back to a query string representation

I have a custom javascript on the client side that I use to build up a querystring and pass over to my asp.net-mvc controller
var templateQueryString = BuildTemplate();
$.ajax({
url: '/MyController/Save?' + templateQueryString,
type: 'post',
dataType: 'json',
success: function (data) {
}
}
and on my controller all of the properties leverage the model binding so it comes in as a single object on the server side. NOTE: that this is a pretty complex object with arrays and arrays of sub objects:
public ActionResult Save(MyTemplate template)
{
}
the issue now is that I need to be able to convert from my C# object back to a string that represents "myTemplateQueryString" on the client side.
Is there any recommended way to take an object and do the "reverse" model binding. They key here is that it generates a string that I could use as a query string again in the future to pass into another asp.ent-mvc controller action.
Here is an example of the querystring that I am storing locally:
<input type="hidden" value="showIds=false&showRisks=false&
amp;statusIds=2&statusIds=1&statusIds=6&statusIds=8&
amp;statusIds=3&statusIds=9&showCompleted=0"
name="filterQueryString" id="filterQueryString">
As #haim770 said it would be easier if you used JSON in the request payload, and not the query string to pass your complex object to the server.
Regarding creating the query string from a model there is not a built-in method that does something like that or any recommended approach as far as i know. An obvious solution is to use reflection and build the query string from your properties.
Assuming your BuildTemplate class looks something like:
public class BuildTemplate
{
public bool ShowIds { get; set; }
public bool ShowRisks { get; set; }
public bool ShowCompleted { get; set; }
public int[] StatusIds { get; set; }
}
You can develop an extension method to convert any object to a QueryString. Here is some initial code you can start with:
public static class ObjectExtensions
{
public static string ToQueryString(this Object obj)
{
var keyPairs = obj.GetType().GetProperties().Select(p =>
new KeyValuePair<string, object>(p.Name.ToLower(), p.GetValue(obj, null)));
var arr = new List<string>();
foreach (var item in keyPairs)
{
if (item.Value is IEnumerable && !(item.Value is String))
{
foreach (var arrayItem in (item.Value as IEnumerable))
{
arr.Add(String.Format("{0}={1}", item.Key, arrayItem.ToString().ToLower()));
}
}
else
arr.Add(String.Format("{0}={1}", item.Key, item.Value.ToString().ToLower()));
}
return "?" + String.Join("&", arr);
}
}
Then you can easily invoke this code on any object to generate a query string:
var person = new BuildTemplate() { StatusIds = new []{ 1, 5, 8, 9 }, ShowRisks = true };
var queryString = person.ToQueryString();
This would generate a query string like:
"?showids=false&showrisks=true&showcompleted=false&statusids=1&statusids=5&statusids=8&statusids=9"
This query string should work just fine with the default model binder for the BuildTemplate class.

Unable to send JSON data to MVC controller

I have a JavaScript function that looks as follows:
function exportToExcel() {
$.ajax({
url: "/eBird/ExportToExcel",
data: jsonSightingData,
type: 'POST',
contentType: 'application/json'
});
}
My MVC controller looks like this:
public ActionResult ExportToExcel(List<Entities.MyClass> data)
{
try
{
...
}
catch (System.Exception exception)
{
...
}
MyClass defintion is:
public class MyClass
{
public string comName { get; set; }
public int howMany { get; set; }
public double lat { get; set; }
public double lng { get; set; }
public string locID { get; set; }
public string locName { get; set; }
public bool locationPrivate { get; set; }
public string obsDt { get; set; }
public bool obsReviewed { get; set; }
public bool obsValid { get; set; }
public string sciName { get; set; }
}
The class matches the JSON data coming in exactly. The problem is that when my controller method is called, 'data' is always NULL. My understanding was that the MVC model binder would automatically bind the JSON data to my MyClass list. But it doesn't appear to be working.
Sample JSON is as follows:
[{"comName":"Great Black-backed Gull","lat":42.4613266,"lng":-76.5059255,"locID":"L99381","locName":"Stewart Park","locationPrivate":false,"obsDt":"2014-09-19 12:40","obsReviewed":false,"obsValid":true,"sciName":"Larus marinus"}]
Use a General Object (Like JContainer) to "capture" the incoming data. or even Object if you are not sure what you get.
Then see what you have inside.
I use an external deserializer to convert json back to class. (using .ToString() to make it readable to the serializer)
(try Json.Net)
Also - make sure that the JSON is not converted into Unicode. I've had an issue with that as well.
another remark - I think content type should be application/json.
Read this: SO about json content type
Run Fiddler and capture Json sent to controller. The controller expects a List but looks like you are sending single object. Stuff coming in as null happens to many of us. I'll try and run what you have. Can you also mess with controller and give it just MyClass coming in?

Categories

Resources