Json Deserialization in an ASP.NET not working properly - asp.net

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.

Related

Avoid auto lowercase first letter in asp.net json response

In my asp.net razor project, json response always lowercase the first letter, which is annoying. Since I would then deal with different names from backend to frontend.
My Class:
[JsonProperty("Test")]
public string Test { get; set; } => json responce: Test (good)
public string Test2 { get; set; } => json responce: test2 (bad)
[JsonPropertyName("Test3")]
public string Test3 { get; set; } => json responce: test3 (bad)
Can I avoid adding a JsonProperty markup on every value field?
You can create your custom formatter or use DefaultContractResolver by giving NamingStrategy. For e.g. check below code:
User user = new User
{
UserName = "jamesn",
Enabled = true
};
DefaultContractResolver contractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
string json = JsonConvert.SerializeObject(user1, new JsonSerializerSettings
{
ContractResolver = contractResolver,
Formatting = Formatting.Indented
});
Console.WriteLine(json);

Properly receive a nested object via post

I'm trying to send a complex object as a form object over to a mvc controller. However I just receive a new object with default values.
Here's the object (just a bit trimmed to make it simpler for the example)
public class AddProjectPopupModel
{
public long SelectedCountryId;
public Project ResultProject { get; set; }
}
public class Project
{
public long Number;
public string Name;
}
And here's how I create the form:
#using (Html.BeginForm("AddProjectResult", "Popups", FormMethod.Post, new { id = "addProjectForm"}))
{
#Html.EditorFor(model => model.ResultProject.Number, new { htmlAttributes = new { Id = "number", Class = "validate", Value = 0 } })
#Html.EditorFor(model => model.ResultProject.Name, new { htmlAttributes = new { Id = "name", Class = "validate" } })
}
Now I have a button which calls the following javascript:
var form = $("#addProjectForm");
var data = form.serialize();
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result) {
debugger;
}
});
And the controller:
[HttpPost]
public ActionResult AddProjectResult(AddProjectPopupModel model)
{
return Json(new { Success = true });
}
I've also tried to change the controller parameters to:
public ActionResult AddProjectResult(long SelectedCountryId, Project ResultProject)
And here the SelectedCountryId gets filled properly, but not the Project.
I'd love to use the whole AddProjectPopupModel as parameter and not it's specific values.
However I can't figure out to do it properly.
Fiddler output for the call:
Debugger values in controller:
Your problem is that in your project object you're using fileds
public class Project
{
public long Number;
public string Name;
}
and they should be properties so they can be navigated to
public class Project
{
public long Number { get; set; }
public string Name { get; set; }
}
This should work
I recommend reading Model Binding for more info

Web Api POST for inserting data with Complex type is always null

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

How to create ASP .NET MVC4 Web API to search my multiple parameters

How to create ASP.NET MVC4 json Web API
which allows to search products by id, barcode, search term or retrieve
all products since date ?
I tried to use ASP.NET MVC4 controller below.
Calling
http://localhost:52216/admin/api/Products/GetSince?since=2014-03-16%2021:47:29&_=1395007124964
returns error
Multiple actions were found that match the request:
System.Net.Http.HttpResponseMessage GetSince(System.String) on type MyApp.Controllers.ProductsController\r\n
System.Net.Http.HttpResponseMessage GetId(System.String) on type MyApp.Controllers.ProductsController"
How to fix this ?
This code looks ugly, it contains number of similar methods.
Which is best way to create such API ?
How to improve this code ?
Http GET method should used but method names and signatures can changed.
ASP.NET/Mono MVC4, jquery, jquery UI are used. Windows 2003 server should also supported, so .NET 4.5 or MVC5 cannot used.
public class ProductsController : ApiController
{
[HttpGet]
public HttpResponseMessage GetSince([FromUri]string since))
{
var toodelist = GetProducts(since, null, null, null);
return Request.CreateResponse(HttpStatusCode.OK,
new { products = toodelist.ToArray() });
}
[HttpGet]
public HttpResponseMessage GetId([FromUri]string id)
{
var toodelist = GetProducts(null, null, id, null);
return Request.CreateResponse(HttpStatusCode.OK,
new { products = toodelist.ToArray() });
}
[HttpGet]
public HttpResponseMessage GetBarcode([FromUri]string barcode)
{
var toodelist = GetProducts(null, barcode, null, null);
return Request.CreateResponse(HttpStatusCode.OK,
new { products = toodelist.ToArray() });
}
[HttpGet]
public HttpResponseMessage GetTerm([FromUri]string term)
{
var toodelist = GetProducts(null, null, null, term);
return Request.CreateResponse(HttpStatusCode.OK,
new { products = toodelist.ToArray() });
}
static List<Product> GetProducts(string since, string barcode, string id, string term)
{
... retrieves list of product from database using specified search criteria
if not null
}
}
How about using a search criteria DTO like this?
public class SearchCriteria
{
public int? Id { get; set; }
public DateTime? Since { get; set; }
// Other properties
}
Action method will be like this.
public class ProductsController : ApiController
{
public HttpResponseMessage GetProducts([FromUri]SearchCriteria crit))
{
// Validate and clean crit object
var list = GetProducts(crit);
// return list
}
}
GetProducts can return the list of products based on the properties set in SearchCriteria object. If a query string field is not present, corresponding property will be null.

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