Web Api POST for inserting data with Complex type is always null - asp.net

I'm quite new to Web-Api concepts. Trying to insert data using the basic project provided by Microsoft (Adding a simple Test Client to ASP.NET Web API Help Page).
http://blogs.msdn.com/b/yaohuang1/archive/2012/12/02/adding-a-simple-test-client-to-asp-net-web-api-help-page.aspx
Below is the code for Inserting data into Headoffice table.(HeadofficeID int ,HeadofficeName varchar(50),Notes varchar(1000),Isactive bit)
[POST("create")]
public HttpResponseMessage Post([FromUri]HeadOfficeModel headOffices)
{
if (_headOfficeBLL.Insert(headOffices) > 0)
return Request.CreateResponse(HttpStatusCode.Created, headOffices);
else
return Request.CreateResponse(HttpStatusCode.BadRequest, headOffices);
}
Headofficemodel Class
public partial class HeadOfficeModel : AtlAuthenticationModelBase
{
public int HeadOfficeId { get; set; }
public string HeadOfficeName { get; set; }
public string Notes { get; set; }
public bool IsActive { get; set; }
}
In the front end when i try to send the data from URI or Body only null values are getting inserting. While debugging all i can see in Headoffice model is null values.Below are the different ways i tried to insert data
1) {"HeadOfficeName":"TestHO1", "Notes":"notes", "IsActive":true}
2) {"TestHO1", "notes", true}
3) ={"headOffices":{"HeadOfficeName":"TestHO1","Notes":"notes","IsActive":false}}
and also tried to change the code as below
public HttpResponseMessage Post([FromUri]HeadOfficeModel headOffices)
public HttpResponseMessage Post([FromBody]HeadOfficeModel headOffices)
public HttpResponseMessage Post([ModelBinder]HeadOfficeModel headOffices)
Been trying to fix this from two days. When i send the data as complex type its not working else as separate parameters (changing the method to accept parameters) its working fine
public int Post(string Name, string Notes, bool Active)
{
HeadOfficeModel objHOM = new HeadOfficeModel();
objHOM.HeadofficeName = Name;
objHOM.Notes = Notes;
objHOM.IsActive = Active;
return _headOfficeBLL.Insert(objHOM);
}
Below is the html code where i m hiting while inserting
<script>
testClientModel = {
HttpMethod: '#Model.ApiDescription.HttpMethod',
UriPathTemplate: #Html.Raw(Json.Encode(Model.ApiDescription.RelativePath)),
UriParameters: [
#foreach (var parameter in Model.ApiDescription.ParameterDescriptions)
{
if (parameter.Source == System.Web.Http.Description.ApiParameterSource.FromUri)
{
#:{ name: "#parameter.Name", value: "" },
}
}
],
Samples: {
#Html.Raw(#String.Join(",", Model.SampleRequests.Select(s => String.Format("\"{0}\": \"{1}\"", s.Key, HttpUtility.UrlEncode(s.Value.ToString()))).ToArray()))
},
BaseAddress: '#applicationPath'
};
</script>
Can you please help me where am i going wrong. Attaching screenshot.
Entered both in URI and Body just to show that i tried different ways.
enter image description here

Related

Json Deserialization in an ASP.NET not working properly

I have an API that returns the following response as string
[
{
"id": "62a9f8f90346133662624bd3",
"referenceID": "test1",
"additionalInfoList": ["string"]
},
{
"id": "62a9fba50346133662624bd4",
"referenceID": "111",
"additionalInfoList": ["string"]
}
]
edit: where the exact formatting of the string is as follows with escaping backslashes:
"[{\"id\":\"62a9f8f90346133662624bd3\",\"referenceID\":\"test1\",\"additionalInfoList\":[\"string\"]},{\"id\":\"62a9fba50346133662624bd4\",\"referenceID\":\"111\",\"additionalInfoList\":[\"string\"]}]"
and the following class model
public class IncidentModel
{
public string id { get; set; }
public string referenceID { get; set; }
public List<string> AdditionalInfoList { get; set; }
}
The problem arises in the code to deserialize. While I get a list with 2 elements, there is no data, only some generic metadata and fields that are not part of the model.
public async Task<JsonResult> OnGetIncidentsAsync()
{
List<IncidentModel> incidents = new List<IncidentModel>();
using (var httpClient = new HttpClient())
{
using (HttpResponseMessage response = await httpClient.GetAsync("api/Incident/GetAllIncidents.json/"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
incidents = JsonConvert.DeserializeObject<List<IncidentModel>>(apiResponse);
}
}
return new JsonResult(incidents);
}
The attached image shows the data inside incidents.
How can I solve this?
So it turns out in Pages, I had a page named Incident. Because I use Razor pages, this page had a Model, named IncidentModel.cshtml.cs which was overriding the IncidentModel.cs from the Models folder. Renaming the model fixed the problem.

Handle querystring coontaining [] in asp.net

What is the best way to handle the queries[search] and sorts[Driver1] parameters in the following querystring in asp.net?
?queries[search]=greenock&id=20&sorts[Driver1]=1
I tried using this model but only id was bound:
public class ICRSRequestModel
{
public int ID { get; set; }
public ICollection<string> Sorts { get; set; }
public ICollection<string> Queries { get; set; }
}
I don't have the option of changing the requesting application unfortunately, and the string contained inside [] could be any unknown value.
If the property is
public ICollection<string> Queries { get; set; }
Then the query string would need to be
?queries[0]=greenock
you would need to change the property to
public Dictionary<string, string> Queries { get; set; }
so that the query string could be
?queries[search]=greenock
The key will be "search" and the value will be "greenock"
Note this will only work for a single queries value. ?queries[search]=greenock?queries[anotherKey]=anotherValue will not work
Sorry, not got 50 rep points yet else I would have commented with this probably useless comment, but here goes..
I'm sure there's a better way using MVC bindings but if all else fails it might be worth taking the QueryString from the Server.Request object and splitting the string up to extract the information you want. You can get them in to a keyvaluepair collection using the code I had lying around in a project, I'm sure it can be manipulated for your needs.
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (string part in queryString.Split(new char[] { '&' }))
{
if (!string.IsNullOrEmpty(part))
{
string[] strArray = part.Split(new char[] { '=' });
if (strArray.Length == 2)
{
dictionary[strArray[0]] = strArray[1];
}
else
{
dictionary[part] = null;
}
}
}

Web method return JSON result in two level (In kendoUI Datasource)

This the server side Code
[System.Web.Services.WebMethod]
public static object GetDevelopers()
{
return new DqListViewModel(DQContext.Service._IDqs_IssueRepository.SelectList().ToArray(), 10);
}
View Model
public class DqListViewModel
{
public Array Data { get; set; }
public int Count { get; set; }
public DqListViewModel(Array data, int count)
{
this.Data = data;
this.Count = count;
}
}
This is the JSON return Value
why the JSON result has tow level object. I am not supposed to have "d" level?
Please check the below link. http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/
This is not an issue from Knedo-ui but it is the functionality of the Asp.net
Please try with the below link, may be it will help you.
How to bind JSON child array to Kendo grid

List<T> caching, class iteration, count property

Hy,
I have created a custom List, which tried to cache, but when getting back from cache, the cached object count is 0. Example code below:
List<CategoryEntry> categs = (List<CategoryEntry>)EPiServer.CacheManager.Get("test");
if(categs == null || categs.Count == 0)
{
categs = ConstructCategories();
EPiServer.CacheManager.Add("test", categs);
}
//Further down displaying the categories
UseCase:
First Pageload (after build) cache is empty, categs will be null,
Second Pageload cache will be, but will fail from get from there becouse categs.Count will be 0 and reconstructs the cache again and again....
the CategoryEntry class:
[serializable]
public class CategoryEntry{
public string Title { get; set; }
public string URL { get; set; }
public int CategoryId { get; set; }
public int CompanyPageId { get; set; }
public int ParentCategoryEntryId { get; set; }
public int Indent { get; set; }
}
The problem should be when saving the cache bc. it is saved as object, and when we get the cache we Cast to List<CategoryEntry>.
Also figured out if i do this with a List<string> instead of using List<CategoryEntry>
then the caching works perfectly!.
Example with List<string> which is working:
List<string> test = (List<string>)EPiServer.CacheManager.Get("sindex");
if (test == null)
{
test = new List<string>();
test.Add("item1");
test.Add("item2");
test.Add("item3");
test.Add("item4");
test.Add("item5");
EPiServer.CacheManager.Add("sindex", test);
}
else
{
Response.Write("It works: elements "+ test.Count);
}
Another Tryout was that i have cached a simple instance of CategoryEntry and that also works, the problem is when i try to save as List<CategoryEntry>
Any help Would be apreciated, thank you.

How to post JSON data to SQL using ajax post & knockout

I have a pretty straightforward view model:
var ProjectViewModel = {
ProjectName: ko.observable().extend({ required: "" }),
ProjectDescription: ko.observable().extend({ required: "" }),
ProjectStartDate: ko.observable(),
ProjectEndDate: ko.observable()
};
I want to save this data that is located in my viewmodel to my SQL server.
I have a class defining this View Model in my Server Side Code:
public class Projects
{
public string ProjectName { get; set; }
public DateTime ProjectStartDate { get; set; }
public DateTime ProjectEndDate { get; set; }
public string ProjectDescription { get; set; }
}
I also have this web method to receive the code:
[WebMethod]
public bool SaveProject(string[] JSONDATA)
{
TaskNinjaEntities entities = new TaskNinjaEntities();
foreach (var item in JSONDATA)
{
Console.WriteLine("{0}", item);
}
return true;
}
And finally I have this POST that does not want to send the data to the server:
function SaveMe() {
var data = ko.toJSON(ProjectViewModel);
$.post("CreateProject.aspx/SaveProject", data, function (returnedData) {
});
}
I get nothing from the returned data in this post method, also added breakpoint in server side code, and it doesn't hit it at all. My URL is correct and the Viewmodel converts to JSON without hassle.
Make the web method static.
[WebMethod]
public static bool SaveProject(string[] JSONDATA)
{
TaskNinjaEntities entities = new TaskNinjaEntities();
foreach (var item in JSONDATA)
{
Console.WriteLine("{0}", item);
}
return true;
}

Resources