Im passing array data from angularjs to mvc controller
This is my angularjs code
$http({
url: '/Login/InsertDetails',
method: 'POST',
data: JSON.stringify(Data),
headers: { 'content-type': 'application/json' }
})
Json Data is
$scope.details = [{
name: "ammin",
age: "16",
city: "NY",
add: "true",
sal: 100
}, {
name: "joe",
age: "80",
city: "CH",
add: false,
sal: 200
}];
var Data = {
one: $scope.details
}
And in my controller i have method Insert with list parameter
public JsonResult Insert(List<Personel> P)
{
}
View Model class is like this
public class Personel
{
public string name { get; set; }
public int age { get; set; }
public string city { get; set; }
public string add { get; set; }
public string sal { get; set; }
}
But im getting null values in action method when i post the data from angularjs. what type of parameter should i use in action method
Related
I'm just trying to pass some basic form data through to a web-api via AngularJS $http.
here is the function that called to send data to the API:
$http({
url: "/Portal/GenerateTimeSheets",
method: "POST",
headers: {
'Content-Type': 'application/json'
},
data: angular.toJson($scope.placementForm),
}).then(function (response) {
}), function(response) {
};
Note: if I breakpoint and copy and paste the $scope.placementForm data into postman it works completely fine, but going through a browser is throwing errors.
Here is my api:
[HttpPost]
public void GenerateTimeSheets([FromBody]PlacementModel placement)
{
Console.WriteLine("STUB");
}
and the Placement Model:
[JsonProperty(PropertyName = "candidateName")]
public string CandidateName { get; set; }
[JsonProperty(PropertyName = "clientName")]
public string ClientName { get; set; }
[JsonProperty(PropertyName = "jobTitle")]
public string JobTitle { get; set; }
[JsonProperty(PropertyName = "placementStartDate")]
public string StartDate { get; set; }
[JsonProperty(PropertyName = "placementEndDate")]
public string EndDate { get; set; }
[JsonProperty(PropertyName = "frequency")]
public string TimeSheetFrequency { get; set; }
404 Usually denotes that the url of the request is wrong, You are missing something in the url. Validate your url with the backend. Hope it helps
I'm trying to send an object to the backend with an $http post, but one of the parameters is always null. I'm formatting the dto in the same way when saving a new object and that works fine, but when I try to call the update function it's not working. What am I missing?
This is my controller code:
vm.postUpdateITSM = function (itsm) {
$http({
method: "POST",
url: "api/sources/" + itsm.Id,
data: {
id: itsm.Id,
dto: {
ConnectorType: itsm.Type,
SourceName: itsm.ServerName,
DisplayName: itsm.DisplayName,
Credentials: JSON.stringify(itsm.UserName,
itsm.Password),
Url: itsm.URL,
Settings: JSON.stringify(itsm.ResolveAlerts ? itsm.ResolveAlerts : false,
itsm.AcknowledgeAlerts ? itsm.AcknowledgeAlerts : false,
itsm.SyncInterval,
itsm.IncidentInterval,
itsm.Status ? itsm.Status : "")
}
}
});
}
And on the back end: The dto is always null when called.
public async Task<IHttpActionResult> Update(int id, [FromBody] SourceDto dto)
{
var source = Mapper.Map<Source>(dto);
source.SourceID = id;
source.ServerCount = "";
var res = await SystemActors.SourceManager.Ask(new UpdateSource(source));
var failure = res as Status.Failure;
if (failure != null)
{
return InternalServerError();
}
var success = ((SqlResult<object>) res).Success;
if (!success)
{
return Content(HttpStatusCode.BadRequest, "Failed to update source.");
}
return Ok(new ResponsePackage {Success = true});
}
And this is the SourceDto class:
public class SourceDto
{
public string ConnectorType { get; set; }
public string SourceName { get; set; }
public string DisplayName { get; set; }
public string Credentials { get; set; }
public string Url { get; set; }
public string Settings { get; set; }
}
Your frontend data is formatted a bit wrong - the data parameter should just be the one object your ASP.NET controller is expecting in the [FromBody], your SourceDto model - and the id should be a query string:
method: "POST",
url: "api/sources/" + itsm.Id,
data: {
ConnectorType: itsm.Type,
SourceName: itsm.ServerName,
DisplayName: itsm.DisplayName,
Credentials: JSON.stringify(itsm.UserName,
itsm.Password),
Url: itsm.URL,
Settings: JSON.stringify(itsm.ResolveAlerts ? itsm.ResolveAlerts : false,
itsm.AcknowledgeAlerts ? itsm.AcknowledgeAlerts : false,
itsm.SyncInterval,
itsm.IncidentInterval,
itsm.Status ? itsm.Status : "")
}
});
ASP.NET will apply the request body to the expected model - if it doesn't match, you'll get null
here is my codes.
json_model
var mix = {
MixName: $("#mixname").val(),
MixDesc: tinyMCE.activeEditor.getContent(),
Price: $("#price").val(),
DiseaseMixs: [],
MixProducts: []
}
Add items to DiseaseMixs and MixProducts
$("#DiseaseList").find("tbody tr").each(function (index) {
mix.DiseaseMixs.push({
MixID: parseInt(MixID),
DiseaseID: parseInt($(".diseaseid").eq(index).html()),
ImpactDegree: parseInt($(".derece option:selected").eq(index).html()),
Description: $(".diseaseMixDesc input").eq(index).val()
});
})
$("#productList").find("tbody tr").each(function (index) {
mix.MixProducts.push({
MixID: parseInt(MixID),
ProductID: parseInt($(".productid").eq(index).html()),
MeasureTypeID: parseInt($(".birim option:selected").eq(index).val()),
MeasureAmount: $(".measureAmount input").eq(index).val()
});
})
and end of this process, here is a sample json object that is post.
{
"MixName": "asdasddas",
"MixDesc": "<p>sadasd</p>",
"Price": "123",
"DiseaseMixs": [{
"MixID": 1,
"DiseaseID": 2,
"ImpactDegree": 5,
"Description": "asads"
}, {
"MixID": 1,
"DiseaseID": 3,
"ImpactDegree": 4,
"Description": "aqqq"
}],
"MixProducts": [{
"MixID": 1,
"ProductID": 2,
"MeasureTypeID": 3,
"MeasureAmount": "3"
}, {
"MixID": 1,
"ProductID": 3,
"MeasureTypeID": 2,
"MeasureAmount": "45"
}]
}
ajax post
$.ajax({
url: 'SaveMix',
type: 'POST',
data: JSON.stringify(mix),
contentType: 'application/json; charset=utf-8',
success: function (result) {
console.log(result);
},
error: function (xhr, status) {
alert(status);
console.log(xhr);
}
})
and MVC Model and JSONResult function
Model
public class MixModel
{
public string MixName { get; set; }
public string MixDesc { get; set; }
public float Price { get; set; }
DiseaseMix[] DiseaseMixs { get; set; } //DiseaseMix EntityFramework entity
MixProduct[] MixProducts { get; set; } //MixProduct EF
}
function
[HttpPost]
public JsonResult SaveMix(MixModel mix)
{
bool result = false;
//do something
return Json(new { result = result }, JsonRequestBehavior.AllowGet);
}
and here is the result I get is.
No matter how I tried, I could not bind the model.
What am I doing wrong? Please give me some help.
Thanks in advance.
Model binding is failing because those 2 properties are currently private(which is the default when you don't specify anything explicitly).
Change the 2 properties to public so that model binder can set the values of those.
public class MixModel
{
public string MixName { get; set; }
public string MixDesc { get; set; }
public float Price { get; set; }
public DiseaseMix[] DiseaseMixs { get; set; } //DiseaseMix EntityFramework entity
public MixProduct[] MixProducts { get; set; } //MixProduct EF
}
I also suggests to not mix your view models with entities generated by your ORM. That creates a tightly coupled solution.
The following code is sending null object to MVC controller from Angularjs controller. In the "batarang" $scope is displaying EmployeeInfo object with proper values fill in HTML form. But MVC method is getting all values null. My code is as below
Controller :
Angular.module("myApp", []).controller("EmployeeBasicCtrl", function ($scope, $http) {
$scope.signBox = false;
$scope.SEX = [
{ text: "Non of above", value: "N" },
{ text: "Female", value: "F" },
{ text: "Male", value: "M" },
]
$scope.submitBasicInfo = function () {
$http({
method: 'POST',
url: '/EmployeeInfo/AddEmployee'
}).success(
function (resp) {
$scope.success = resp.success;
$scope.Message = resp.Message;
}
)// success en
} // end of submit form
})// end of controller
HTML:
<form ng-submit="submitBasicInfo()" name="EmployeeBasic" ng-controller="EmployeeBasicCtrl">
<div class="well">
<input type="hidden" name="EmpID" />
<div class="panel panel-heading panel-primary">
<div class="panel-heading"><h3> Personal Information </h3></div>
<label> First Name </label>
<input name="Fname" class="form-control" ng-model="EmployeeInfo.Fname" required />
<small ng-show="EmployeeBasic.Fname.$touched && EmployeeBasicEmployeeBasic.Fname.$invalid">First Name is mandatory</small><br />
..........
MVC Controller:
[HttpPost]
public JsonResult AddEmployee(EmployeeInfo para)
{
return Json(new {success="success" },JsonRequestBehavior.AllowGet);
}
EmployeeInfo class:
public class EmployeeInfo
{
public string EmpID { get; set; }
public string Fname { get; set; }
public string Sname { get; set; }
public DateTime DOB { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Gender { get; set; }
public string UnitNo { get; set; }
public string StreetNo { get; set; }
public string Suburb { get; set; }
public string StateID { get; set; }
public string PostCode { get; set; }
Help is appreciated
this is because you are not posting the data through service,that's why you got null in backend
your post request should be like
$scope.EmployeeInfo ={'Fname':'',EmpID:''....all your child obj of EmployeeInfo }
$scope.submitBasicInfo = function (EmployeeInfo) {
$http({
method: 'POST',
url: '/EmployeeInfo/AddEmployee',
data: EmployeeInfo, // what data you want to send
headers: {'Content-Type': 'application/json'}
});
}
you can pass EmployeeInfo object from view
<form ng-submit="submitBasicInfo(EmployeeInfo)" name="EmployeeBasic" ng-controller="EmployeeBasicCtrl">
Client code:
var basket = {
products: [],
user: { name: "schugh" }
};
$("#basket table tr").each(function (index, item) {
var product = $(item).data('product');
if (product) {
basket.products.push(product);
}
});
$.ajax({
url: "http://localhost:12116/basketrequest/1",
async: true,
cache: false,
type: 'POST',
data: JSON.stringify(basket),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert(result);
},
error: function (jqXHR, exception) {
alert(exception);
}
});
Server code:
Post["/basketrequest/{id}"] = parameters =>
{
var basketRequest = this.Bind(); //basketrequest is null
return Response.AsJson(basketRequest , HttpStatusCode.OK);
};
Other model classes:
[Serializable]
public class BasketRequest
{
public User User;
public List<Product> Products;
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
public ProductStatus ProductStatus { get; set; }
}
public enum ProductStatus
{
Created,
CheckedBy,
Published
}
public class User
{
public string Name { get; set; }
}
The code in the Nancy Module this.Bind(); returns null. If I change the Complex object to just List<Product>, i.e. with no wrapper BasketRequest, the object is fine...
Any pointers?
EDIT: JSON posted:
{
"User": {
"Name": "SChugh"
},
"Products": [{
"Id": 1,
"Name": "Tomato Soup",
"Category": "Groceries",
"Price": 1
}, {
"Id": 2,
"Name": "Yo-yo",
"Category": "Toys",
"Price": 3.75
}]
}
Your BasketRequest object should implement properties instead of fields. So
public class BasketRequest
{
public User User { get; set; }
public List<Product> Products { get; set; }
}
also you should probably use the generic method too
this.Bind<BasketRequest>();