Binding array to specifed object in asp.net web api - angularjs

[HttpPost, Route("api/EtiketAPI/EtiketEkle/{makaleId}")]
public HttpResponseMessage EtiketEkle(string makaleId,Etiket[] values)
I have been recently using web api. I am stuck to bind an array which comes from web request and the request method is post method. Is there any way to bind data comes from request to my specified object ?
I am sending data with angularjs. Here is data form
[{"EtiketId":1,"EtiketAdi":"Microsoft","EtiketRadi":"microsoft","Makaleler":null},{"EtiketId":2,"EtiketAdi":".net","EtiketRadi":"-net","Makaleler":null}]
and my class
public class Etiket
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EtiketId { get; set; }
public string EtiketAdi { get; set; }
public string EtiketRadi { get; set; }
public virtual ICollection<Makale> Makaleler { get; set; }
}

here are you answers :
Sending binary data along with a REST API request
Processing binary data in Web API from a POST or PUT REST request

Related

Image file with AngularJS and ASP NET MVC

Please help me!
My Controller can't recent Image File from angular.
Here my angular file
Here my Controller
Class Product:
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int Price { get; set; }
public byte[] Image { get; set; }
}
I try user HttpPostedFileBase in My Controller but not work.
Should I convert File to byte array before call Controller Function?
Take a look at these:
File Upload Using Angular JS and ASP.NET MVC 5
File Upload with Angular and ASP.NET MVC 4
If you're not uploading large images, you could also convert them to Base64 strings and post them to server.

How to send an array items from UI to MVC Controller

I have an array of objects in UI that is being sent to MVC Controller . The Array of objects look like :
`DoorId`,`DoorName` and an array of `Schedules`. `Schedules` array has `ScheduleId` and `ScheduleName`.
Now how to send it to MVC Controller ? So that , every DoorId and it's associated ScheduleId can be extracted separately to form another obeject ?
Presently , I am sending the DoorId Array and the ScheduleId array separately ,
But I do not want to do that . I want to send the entire array itself.
public async Task<ActionResult> AddGroup(string[] DoorIds, string[] scheduleEntity)//AccessGroupEntity entity, string accountId
{
GroupEntity groupEntity = new GroupEntity();
var doorScheduleList = new List<DoorInfoEntity>();
for(int i=0;i< DoorIds.Length;i++)
{
doorScheduleList.Add(new DoorInfoEntity()
{
DoorId = DoorIds[i],
ScheduleId = scheduleEntity[i]
});
}
accessGroupEntity.DoorItems = doorScheduleList;
And then Parse it as Doors[index].DoorId and Doors[index].ScheduleId to form 'DoorInfoEntity` object.
How to do it ?
I tried object[] Doors but it says Object does not contain a definition for DoorId or ScheduleId.
You need an object graph in C# that the modelbinder can bind the posted data to which mimics the object graph you have in your JavaScript. For example:
public class Door
{
public Guid DoorId { get; set; }
public string DoorName { get; set; }
public List<Schedule> Schedules { get; set; }
...
}
public class Schedule
{
public Guid ScheduleId { get; set; }
...
}
Then, you accept the root class as a param in your action:
public async Task<ActionResult> AddGroup(List<Door> doors)
The modelbinder, then, will create the object graph server-side from the posted data.

Json parsing in MVC 4 web api with angularjs

public partial class User
{
public System.Guid UserId { get; set; }
public Nullable<System.Guid> RoleId { get; set; }
public Nullable<long> MembershipNo { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Emaiil { get; set; }
public Nullable<decimal> MobileNo { get; set; }
public string Description { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual Role Role { get; set; }
}
This is my table in DB named Users which is associated with Roles table of DB (as you can see last virtual row at the end above)
Now My problem is simple. I'm using angulars $http.get() method to call my Web Api in MVC 4. When i call it, it gets connected and fetches desired record but it doesn't throw proper result back to .js file or controller.
At .js side I run into error. Every time, it executes .error(jsonResult,config,header,status) .
When I jump on to JsonResult, it shows me below error.
Object
ExceptionMessage: "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
ExceptionType: "System.InvalidOperationException"
InnerException: Object
ExceptionMessage: "Self referencing loop detected for property 'Role' with type
'System.Data.Entity.DynamicProxies.Role_82CA96EA045B1EB47E58B8FFD4472D86502EEA79837B4AE3AD705442F6236E58'.
Path 'Role.Users[0]'."
ExceptionType: "Newtonsoft.Json.JsonSerializationException"
Message: "An error has occurred."
I don't know what's wrong here. Is it json parsing error or something? if so, I've heard and read the articles that webapi in .net handles or throws json itself.
My call happens through
$http.get(apiUrl).success(function (jsonResult, header, config, status) {
debugger;
var number = parseInt(jsonResult.membershipNo) + 1;
$scope.membershipNo = "M" + number;
})
.error(function (jsonResult, header, config, status) {
debugger;
toastr.error('Something went wrong ! Contact Administrator!!!');
});
Edited:
One more thing to mention, .CS side when I fetch single cell value (from DB/table) , it gets returned back to .success() call but when i fetch particular row or all rows, it gets returned to .error() call. I'm using entity frameworkd 6.1.1. and above class is generated by EF-6.1.1.
public partial class Role
{
public Role()
{
this.Permissions = new List<Permission>();
this.Users = new List<User>();
}
public System.Guid RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public Nullable<System.Guid> ModifiedBy { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual ICollection<Permission> Permissions { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Hi you can solve that in 2 easy steps
First Step: Create globalConfig class where you can set ignoring ReferenceLoopHandling (http://james.newtonking.com/json/help/index.html?topic=html/SerializationSettings.htm) and if you crating js app you can set as well to remove xml formaters and always get return from Webapi as JSON string is usefull for debugging. So in your app_start folder add class GlobalConfig like below:
public class GlobalConfig
{
public static void CustomizeConfig(HttpConfiguration config)
{
// Remove Xml formatters. This means when we visit an endpoint from a browser,
// Instead of returning Xml, it will return Json.
//that is optional
config.Formatters.Remove(config.Formatters.XmlFormatter);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
}
Second Step: In Global.asax set your custom configuration to do that please add code below to method Application_Start():
GlobalConfig.CustomizeConfig(GlobalConfiguration.Configuration);
it sounds like:
the problem is that EF is using lazy loading that is not materialized in time of constructing this, on role. EF from early version has switched lazy loading on by default.
Suggested solution
Create subset of you user class, with the parts that you really need.
=> Its bad practise to fetch too much data that you are not gonna need.

Why do Entity Framework classes need a virtual member of an unrelated class

Easier to show by example -- I'm using code-first to construct a database. I have the following classes:
public class Blog
{
public int Id { get; set; }
public string Title { get; set; }
public string AuthorName { get; set; }
public List<Post> Posts { get; set; }
public string BlogCode
{
get
{
return Title.Substring(0, 1) + ":" + AuthorName.Substring(0, 1);
}
}
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public virtual Blog Blog { get; set; }
}
I don't understand why Post needs a public virtual Blog Blog. Does it act as a foreign key in the database to link back to the Blog? It seems like if that were the case you would use the Blog Id.
It does allow the two tables to be related and places a foreign key on Post relating to Blog.
Having public virtual Blog Blog { get; set; } allows you to reference the Blog object from a Post object and then get access to all the properties of the Blog. E.g. myPost.Blog.Id If it used public virtual int BlogId { get; set; }, you would not be able to do this since BlogId would just be an int value.
If your domain objects are lazy loaded, myPost.Blog will not actually be hydrated with data from the database (i.e. no call to the Blog table) until that property is used. As soon as it is used, Entity Framework will make the database call for you and hydrate the object with data from the Blog table. This is part of the beauty of using an ORM... it allows you to focus on the code while it takes care of the database operations.

Entity Framework / RIA Services Include not working

I've got a SL4 / WCF RIA Services / EF 4 application. I'm having trouble getting my Included entity into my SL4 data context.
In the server side service portion of the application, this is my method:
[Query(IsDefault = true)]
public IQueryable<ToolingGroup> GetToolingGroups()
{
var groups = this.ObjectContext.ToolingGroups.Include("MetaData").OrderBy(g => g.Name);
return groups; //breakpoint set here
}
I assigned it to the var groups to allow it to be inspected before the method returns. If I set a breakpoint before the method returns and add a line to my Watch window the MetaData is there:
groups.First().MetaData
When I let the method return and check it in the silverlight ui completed event MetaData is null.
void loadOperation_Completed(object sender, System.EventArgs e)
{
grid.ItemsSource = _toolingContext.ToolingGroups;
UpdateUI(); //breakpoint set here
}
When I do this in my watch window MetaData is null:
_toolingContext.ToolingGroups.First().MetaData
I checked to make sure the ToolingGroup returned by the call to .First() in both cases was the same entity and it was.
Why is MetaData lost (eg. null) between the service method and my ui method?
SOLUTION:
// The MetadataTypeAttribute identifies ToolingGroupMetadata as the class
// that carries additional metadata for the ToolingGroup class.
[MetadataTypeAttribute(typeof(ToolingGroup.ToolingGroupMetadata))]
public partial class ToolingGroup
{
// This class allows you to attach custom attributes to properties
// of the ToolingGroup class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class ToolingGroupMetadata
{
// Metadata classes are not meant to be instantiated.
private ToolingGroupMetadata()
{
}
public int Id { get; set; }
[Include] // Added so MetaData gets serialized
public MetaData MetaData { get; set; }
public Nullable<int> MetaDataId { get; set; }
public string Name { get; set; }
public ToolingCategory ToolingCategory { get; set; }
public int ToolingCategoryId { get; set; }
public EntityCollection<ToolingType> ToolingTypes { get; set; }
}
}
There are two layers at play here, EF and RIA Services. You've handled the EF part. Now you need to tell RIA services to include that property when it serializes your entities across the wire. In your metadata for the entity, add the [Include] attribute. Like this...
[MetadataType(typeof(ToolingGroup.MetaData)]
public partial class ToolingGroup {
private class MetaData {
// adding this attribute tells RIA services
// to also send this property across
[Include]
public MetaData MetaData { get; set; }
}
}
It's a bad coincidence that your type is called "Metadata", the ToolingGroup.MetaData class is the metadata that RIA services uses.

Resources