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.
Related
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
};
}
I have this angular JS controller where I am serialising a view model to json which doesnt deserialise on the backend with a web api.
Here is my angular controller constructor..
constructor($scope, $http, $routeParams: IBookingParams) {
this.http = $http;
//get parameters from Recommendation page
this.bookingView = <IBookingViewModel>{};
this.bookingView.CampaignName = $routeParams.CampaignName;
this.bookingView.CampaignSupplierId = $routeParams.CampaignSupplierId;
this.bookingView.SupplierName = $routeParams.SupplierName;
this.bookingView.MediaChannelNames = $routeParams.MediaChannelNames;
this.bookingView.MediaChannelIds = $routeParams.MediaChannelIds;
let livedate = this.GetJSDate($routeParams.LiveDate);
let liveDateTime = this.GetDateTime(livedate);
this.bookingView.LiveDate = liveDateTime;
//populate the rest of our model
this.bookingView.Action = "from angular";
var model = this.bookingView;
let json = JSON.stringify(model);
this.http({
url: "/api/asdabooking",
method: "POST",
data: json
})
.then((response: any) => {
let test = "";
})
.catch((data: any) => {
let test = "";
});
}
Here is my web api
[HttpPost]
[Route("api/asdabooking")]
public async Task<IActionResult> BuildBookingModel([FromBody]BookingViewModel model)
{
try
{
//model is null??!!
return Ok("");
}
catch (Exception ex)
{
base.Logger.LogError(ex.Message, ex);
return BadRequest(ex.Message);
}
}
This is pretty bizarre, the bookingView view model on the front end matches the fields on the backend view model "BookingViewModel. I have inspected the json and all looks ok.
This is my view model
public class BookingViewModel
{
public string CampaignName { get; set; }
public string CampaignSupplierId { get; set; }
public string SupplierName { get; set; }
public List<string> MediaIds { get; set; }
public List<string> MediaChannelNames { get; set; }
public List<MediaChannelViewModel> MediaChannels { get; set; }
public string Action { get; set; }
public DateTime LiveDate { get; set; }
public List<int> MediaChannelIds { get; set; }
public int SupplierId { get; set; }
public bool SuccessfulSave { get; set; }
/// <summary>
/// Track which tab is updating
/// </summary>
public string TabAction { get; set; }
/// <summary>
/// Price summary - list of media channels (tabs)
/// </summary>
public List<MediaSummaryViewModel> MediaSummaries { get; set; }
public string UserMessage { get; set; }
}
This is my json
Often when I run into this issue it is caused from the types within the JSON object not matching the types of your properties that you defined within your model. I would ensure those types match. It also might help folks interested in answering this question to post a snippet of your JSON object as well as your model class.
mediaChannelIds should be
"mediaChannelIds":[
4,
5]
This is because I was getting an array from a query string using $routeParams by referring to the same parameter more than once which is a bad idea.. better to separate values with a character to get an array because you cant make it typesafe with $routeParams.. it will always give you strings.
In the JSON You can miss out fields or pass null no problem and it will still deserialise, but you can't mismatch types or the whole thing comes back as null.
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
I create entity outside my Project
this is solution Explorer
My entity Post
[Table("Post")]
public partial class Post
{
public int PostID { get; set; }
[Required]
[StringLength(256)]
public string Title { get; set; }
[StringLength(256)]
public string Description { get; set; }
[StringLength(256)]
public string Picture { get; set; }
public int CategoryID { get; set; }
[StringLength(10)]
public string ViewNumber { get; set; }
public int UserID { get; set; }
public DateTime CreateDate { get; set; }
public int LikeNumber { get; set; }
public int? CommentID { get; set; }
}
My Post Controller
[HttpPost]
public ActionResult UpPost(Post model, HttpPostedFileBase txtImg)
{
var db = new ShareImageDbContext();
if (ModelState.IsValid)
{
if (txtImg != null)
{
txtImg.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ txtImg.FileName);
var post = new Post();
post.PostID = model.PostID;
post.Title = model.Title;
post.Description = model.Description;
post.CategoryID = model.CategoryID;
var userSession = new UserLogin();
userSession = (UserLogin)Session[ShareImage.Common.CommonConstants.USER_SESSION];
post.UserID = userSession.UserID;
post.CreateDate = DateTime.Now;
post.Picture = txtImg.FileName;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index", "Homeuser");
}
else
{
ModelState.AddModelError("", "Đăng ảnh thất bại!");
}
}
return View(txtImg);
}
My Post Database
I inserted some post
I want to display all Post on View. And I call Model as below.
#model IEnumerable<Model.EF.Post>
and I call foreach
#foreach (var item in Model)
but it has an error:
Object reference not set to an instance of an object.
I can display my image in Images folder as code following, but I want to show more attribute of Post table such as Title, Discription, CreateDate...
#foreach(var imgPath in Directory.GetFiles(Server.MapPath("~/Images")))
{
var img = new FileInfo(imgPath);
<img src="#Url.Content(String.Format("~/Images/{0}", img.Name))" />
<hr />
}
Please guide me how to fix it, Thanks!
In your view use String.IsNullOrWhiteSpace for strings and
<img src="<%= ResolveUrl(item.Picture) %>" alt="" /> for images
Problem caused because somewhere you do not set or create object. You have reference that has null value. It raises in view or controller. It will be nice if you provide your error message.
In my WebApi controller I have a few methods that return objects retrieved from a database which are serialized to Json. Everything works fine if a method serializes and returns only a single object, it fails when it tries to serialize a collection of objects.
This is my model class:
[Table("Athlete")]
public partial class Athlete
{
public Athlete()
{
Event = new HashSet<Event>();
User = new HashSet<User>();
}
[Required]
[StringLength(32)]
[DisplayName("First name")]
public string FirstName { get; set; }
[Required]
[StringLength(32)]
[DisplayName("Last name")]
public string LastName { get; set; }
[StringLength(32)]
[DisplayName("Sport")]
public string Sport { get; set; }
[Key]
[Column(TypeName = "numeric")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public decimal Athlete_ID { get; set; }
[DataMember]
[Column(TypeName = "numeric")]
public decimal? Team_Team_ID { get; set; }
[NotMapped]
[DisplayName("Team")]
public string TeamName { get; set; }
[JsonIgnore]
public virtual Team Team { get; set; }
[JsonIgnore]
public virtual ICollection<Event> Event { get; set; }
[JsonIgnore]
public virtual ICollection<User> User { get; set; }
}
This works fine:
[HttpGet]
public IHttpActionResult GetById(int id)
{
var athlete = _db.Athlete
.Where(a => a.Athlete_ID == id)
.FirstOrDefault();
if (athlete != null)
{
return Json<Athlete>(athlete);
}
return NotFound();
}
The following method causes a serialization error (System.InvalidOperationException)
(The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.)
The inner exception's message is "Self referencing loop detected for property 'ApplicationInstance' with type 'ASP.global_asax'. Path 'Request.Properties.MS_HttpContext.ApplicationInstance.Context'."
[HttpGet]
public IHttpActionResult GetAllAthletes()
{
var athletes = _db.Athlete.ToArray();
if (athletes != null)
{
return Ok(Json<IEnumerable<Athlete>>(athletes));
}
return NotFound();
}
I've already tried to change the serialization settings in WebApiConfig.cs like in this question but nothing has worked so far.
Any help would be appreciated.
I've managed to find a way to work-around this in a semi-elegant manner. I'm not completely happy with this but a man's gotta do what a man's gotta do.
In case anyone needs this in the future:
Create a class that implements the IHttpActionResult interface:
public class MyJsonResult : IHttpActionResult
{
object _value;
HttpRequestMessage _request;
public MyJsonResult(object value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(_value), Encoding.UTF8, "application/json"),
RequestMessage = _request,
StatusCode = HttpStatusCode.OK
};
return Task.FromResult(response);
}
}
Then use it in a following way:
[HttpGet]
public IHttpActionResult GetAllAthletes()
{
var athletes = _db.Athlete;
if (athletes != null)
{
return new MyJsonResult(athletes, Request);
}
return NotFound();
}