Data received from angularjs to MVC controller is null - angularjs

Dears, I have two classes Master and detail named by Raterequest and Raterequestdetails. I have created a viewmodel contains both of them.
in Angularjs i have an object contains rate and a list contains orderdetails.
when i debug the controller the data received is null for both
here is the code
Rate request class
public class RateRequests
{
public int RateRequestsID { get; set; }
public DateTime RateRequestsDate { get; set; }
public string RateRequestName { get; set; }
public string RateRequestType { get; set; }
public string RateRequestMode { get; set; }
}
Rate request details class
public class RateRequestsLines
{
public int RateRequestsLinesID { get; set; }
public int RateRequestsID { get; set; }
[ForeignKey("RateRequestsID")]
public virtual RateRequests RateRequestsFK { get; set; }
public short FCLCNTRS { get; set; }
public short FCLCNTRSSIZE { get; set; }
public string FCLCNTRSTYPE { get; set; }
}
Rate request view model
public class RateRequestViewModel
{
public RateRequests rate { get; set; }
public IEnumerable<RateRequestsLines> ratelines { get; set; }
}
Angularjs
var linkers = angular.module("linkers", [])
.service("linkersSrv", function ($http) {
var urlBase = "/LinkersEgypt/";
this.save = function (url, ratee) {
return $http({
method: "POST",
url: urlBase + "/" + url,
data: ratee,
̶a̶s̶y̶n̶c̶:̶ ̶f̶a̶l̶s̶e̶,̶
})
};
})
.controller("linkersCon", function ($scope, linkersSrv) {
$scope.fcl = [];
$scope.addFCL = function () {
$scope.fcl.push({ FCLCNTRS: $scope.ncntrs, FCLCNTRSSIZE: $scope.csize, FCLCNTRSTYPE: $scope.ctype });
console.log($scope.fcl);
}
$scope.save = function () {
var ratee = {
rate: {
RateRequestsDate: $scope.rdate,
RateRequestName: $scope.rname,
RateRequestType: $scope.rtype,
RateRequestMode: $scope.smode
},
RateRequestsLines: $scope.fcl
};
console.log(ratee);
var promisepost = linkersSrv.save("RateRequest/AddAllRate", ratee);
promisepost.then(function () {
toastr.success("Successfully saved");
})
}
})
Rate controller
[HttpPost]
public JsonResult AddAllRate (RateRequestViewModel rate)
{
return new JsonResult();
}
Any help
Thanks in advance

Related

Always getting null value when send object with fromData other value from React

I have send a formData from react app with some value and image files and i also want to send a obj with same formData on .net core api
Here is my class
[Bind]
public class ServiceInfo
{
public int id { get; set; }
[NotMapped]
public IFormFile[] ImgFile { get; set; }
[NotMapped]
public IFormFile ImgFilen { get; set; }
//public int { get; set; }
public string title { get; set; }
public string serImg1 { get; set; }
public string serImg2 { get; set; }
public string serImg3 { get; set; }
public string serImg4 { get; set; }
public int serCategoryId { get; set; }
public SerCategory serCategory { get; set; }
public string time { get; set; }
public string location { get; set; }
public string serviceClose { get; set; }
public string serviceOpen { get; set; }
public int CompanyInfoId { get; set; }
public virtual CompanyInfo companyInfo { get; set; }
public string serviceDetails { get; set; }
public string offeredServices { get; set; }
public bool active { get; set; }
public bool status { get; set; }
public string extraServices { get; set; }
public string whyUs { get; set; }
}
.net core controler:
serCategory always getting null
[Route("PotService")]
[HttpPost]
public IActionResult Post([FromForm] ServiceInfo service)
{
//using (MemoryStream stream = new MemoryStream())
//{
// ImgFile.CopyToAsync(stream);
// service.Data = stream.ToArray();
//}
if (string.IsNullOrWhiteSpace(_rootPath.WebRootPath))
{
_rootPath.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "Images");
}
string uploadsFolder = Path.Combine(_rootPath.WebRootPath);
int index = 0;
foreach (var item in service.ImgFile)
{
index++;
if (item != null)
{
var uniqueFileName = service.title.ToString()+index.ToString()+ DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
switch (index)
{
case 1 :
service.serImg1 = uniqueFileName;
break;
case 2:
service.serImg2 = uniqueFileName;
break;
case 3:
service.serImg3 = uniqueFileName;
break;
case 4:
service.serImg4 = uniqueFileName;
break;
}
}
}
//bool result = _serManager.AddService(service);
foreach (var item in service.ImgFile)
{
if (item != null)
{
var uniqueFileName = service.title.ToString() + index.ToString() + DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
item.CopyTo(fileStream);
}
}
}
return Ok(true);
}
And react code :
const formData = new FormData();
formData.append("id", 0);
formData.append("CompanyInfoId", activeComId);
formData.append("title", data.title);
formData.append("time", "");
formData.append("location", data.location.value);
formData.append("serviceClose", data.serviceClose.value);
formData.append("serviceOpen", data.serviceOpen);
formData.append("serviceDetails", data.serviceDetails);
formData.append("serCategoryId", data.serType.id);
formData.append("serCategory", data.serType);
formData.append("offeredServices", data.offeredServices);
formData.append("active", false);
formData.append("status", false);
formData.append("extraServices", data.extraServices);
formData.append("whyUs", data.whyUs);
formData.append("ImgFile", data.serImg1);
formData.append("ImgFile", data.serImg2);
formData.append("ImgFile", data.serImg3);
formData.append("ImgFile", data.serImg4);
for (const [key, value] of formData.entries()) {
console.log(key, value);
}
console.log(data.serType);
const res = await fetch(serPost, {
method: "POST",
body: formData,
});

Join 2 services and use on Controller on ASP.NET Core

I have a view Model:
public class CountViewModel
{
public int NewsLetterEmailCount { get; set; }
public int CurrentMonthNewsLetter { get; set; }
public int NewsLetterPercentage { get; set; }
}
then I create the second ViewModel that want to list of title:
public class AdminDashboardUnreadMessage
{
[Display(Name = "عنوان")]
public string Title { get; set; }
//public List<AdminDashboardUnreadMessage>
AdminDashboardUnreadMessages { get; set; }
}
I have a ticket Table, these are my 2 services:
public async Task<CountViewModel> AdminContentCount()
{
CountViewModel adminContetnCount = new CountViewModel()
{
UserCount = await _userRepository.UserCount(),
CurrentMonthUser = await _userRepository.CurrentMonthUser(),
NewsLetterEmailCount = await _newsLetterRepository.NewsLetterEmailCount(),
CurrentMonthNewsLetter = await _newsLetterRepository.CurrentMonthNewsLetterEmail(),
return adminContetnCount;
}
public async Task<List<AdminDashboardUnreadMessage>> ShowUnReadTicketMessages()
{
return await _userRepository.ShowUnReadTicketMessages();
}
How can I use 2 services on my service
I mean I don't want to use from View Data
I think you need to define a new ViewModel like this :
public class NewViewModel
{
public CountViewModel CountModel { get; set; }
public AdminDashboardUnreadMessage AdminDashboardModel { get; set; }
}
And now you need to return this object as a result of a newly created service which responsible to aggregate the result of two different services.
public async Task<NewViewModel> NewService()
{
var adminContetnCount = await AdminContentCount();
var dashboard = await ShowUnReadTicketMessages();
return new NewViewModel
{
CountModel = adminContetnCount,
AdminDashboardModel= dashboard
};
}

post array of string from angular js controller to asp controller

I am using visual studio 2017 with asp mvc 5.0 and angularJS v1.6.10. I need to send object from angularJS to asp controller via $http service see the following code
public class Patient
{
public int Age { get; set; }
public byte Gender { get; set; }
public bool IsSmoker { get; set; }
public string[] Symptoms { get; set; }
public bool FractionWithTbPatient { get; set; }
public bool PreviousTbInfection { get; set; }
public bool Inheritedcysricfibrosis { get; set; }
public bool Inheritedasthma { get; set; }
public bool Smokermother { get; set; }
public bool OrganicDust { get; set; }
public bool FractionWithanimals { get; set; }
public bool PreviousSurgery { get; set; }
public bool Longbonebroken { get; set; }
public bool Pregnant { get; set; }
public bool CancerInfection { get; set; }
public bool LongTimeInBed { get; set; }
public bool PreviousInfectionWithPulmonaryEmbolism { get; set; }
}
and the asp controller method is the following
public class ConditionDiagnosisController : Controller{
[HttpPost]
public void GetCaseResult(Patient patient)
{
int i = 0;
i++;
}
}
and the angularJS controller is the follwoing
myApp.controller("mainController",
function ($scope, $http) {
var patient = new Object();
patient.Age = 1;
patient.Gender = 0;
patient.IsSmoker = false;
patient.Inheritedasthma = false;
patient.Symptoms = ['x','y'];
patient.Pregnant = false;
patient.FractionWithTbPatient = false;
patient.PreviousTbInfection = false;
patient.Inheritedcysricfibrosis = false;
patient.Inheritedasthma = false;
patient.Smokermother = false;
patient.OrganicDust = false;
patient.FractionWithanimals = false;
patient.PreviousSurgery = false;
patient.Longbonebroken = false;
patient.Pregnant = false;
patient.CancerInfection = false;
patient.LongTimeInBed = false;
patient.PreviousInfectionWithPulmonaryEmbolism = false;
$scope.go = function () {
$http({
method: "POST",
url: "/ConditionDiagnosis/GetCaseResult",
dataType: 'json',
data: $scope.patient,
headers: { "Content-Type": "application/json" }
});
};
});
when I send it I get in the asp method all values of the object correctly else the Symptoms variable which is a string array, I get it null. Any help?
Try with this data : JSON.stringify($scope.patient)
in the ASP.NET class, you should assign the Array in the constructor.
the issue will be that you can't assign the array so the best way is to use List
change the type of Symptoms to List and then in the constructor write this code:
public Patient(){
Symptoms = new List();
}

"Movie" Model taking "Name" property of internal object "Actors"

I am new to Angular and Entity framework.
Here is the code from my AngularJS controller:
$scope.add = function () {
$scope.loading = true;
alert(this.newMovie.Name);
debugger;
$http.post('api/Movie/', this.newMovie).then(function onSuccess(response) {
alert("Added Successfully!!");
debugger;
$scope.showAddMovieForm = false;
$scope.movies.push(response);
$scope.loading = false;
}).catch(function (response) {
$scope.error = "An Error has occured while adding movie! :(" + response.data;
$scope.loading = false;
});
};
Here is how the Action method looks in my MovieController in MVC:
public HttpResponseMessage Post(Movie movie)
{
if (ModelState.IsValid)
{
// _db.People.Where(na => movie.Actors.Any(a => a.PersonId == na.PersonId));
_db.Movies.Add(movie);
_db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, movie);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { movieId = movie.MovieId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
Movie Model Class:
public partial class Movie
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Movie()
{
this.Actors = new HashSet<Person>();
}
public int MovieId { get; set; }
public string Name { get; set; }
public Nullable<short> YearOfRelease { get; set; }
public string Plot { get; set; }
public byte[] Poster { get; set; }
public Nullable<int> ProducerId { get; set; }
public virtual Person Producer { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Person> Actors { get; set; }
}
When I put a debugger in the JS code I can see that Angular is passing the object in correct format.
But somehow when it reaches Action, the "Movie" model takes "Name" property value "Actors" object which is part of "Movie" itself.
Not able to understand why "Movie" model is getting the "Name" property of "Actors".
You need to fix the way you are creating your Actors object in Movie object.
Actor should be JS Array of objects and your Movie object should look like below when you debug:
But, in your case Actors is just a single object. Hope it helps.

angularjs $http is throwing error 500 (Internal Server Error) when groupby in linq is used and passed as json

angularjs $http is throwing error 500 (Internal Server Error) when groupby in linq is used and passed as json
I have 2 classes Offer and OfferDetails
public class OfferDetails
{
public long? eventid { get; set; }
public List<Offer> offer { get; set; }
}
public class Offer
{
public long OfferId { get; set; }
public string OfferType { get; set; }
public Nullable<long> EventId { get; set; }
public Nullable<decimal> OfferDiscount { get; set; }
public Nullable<int> NoofPeople { get; set; }
public Nullable<long> UserId { get; set; }
public Nullable<System.DateTime> CreatedDate { get; set; }
public Nullable<System.DateTime> UpdatedDate { get; set; }
public string CreatedIp { get; set; }
public string UpdatedIp { get; set; }
public Nullable<bool> IsActive { get; set; }
}
When I am calling the method offerdetailsjson() using angularjs $http and putting breakpoint on method offerdetailsjson() then it is running fine but $http throws error
public JsonResult offerdetailsjson()
{
List<OfferDetails> r = repository.Offers.GetAll().GroupBy(x => x.EventId).Select(x => new OfferDetails
{
eventid = x.Key,
offer = x.ToList()
}).ToList();
return Json(r);
}
<script>
angular.module('app', []).controller("OfferListCtrl", OfferListController);
OfferListController.$inject = ['$scope', '$http'];
function OfferListController($scope, $http) {
$http({
url: '/Master/offerdetails',
method: 'post',
}).then(function (response) {
debugger
alert(JSON.stringify(response.data));
}, function () { alert('Failed'); });
}
</script>
I will be thankful if someone can help me.

Resources