The question is very simple :-).
I'm a beginner.
Data comes to the controller (WebApi).
If you put an object.
[HttpPost]
public async Task<IActionResult> AddOrder(Object [] orderR)
ValueKind = Object : "{"product":{"id":"72ae28f2-4ad3-4e97-5a7b-
08d8db1aac26","code":"666666","name":"test6","price":6,"category":"test6","orrderItems":"320d57eb-
3333-45d2-f497-08d8d66a0d39"},"quality":1}"
ValueKind = Object : "{"product":{"id":"72ae28f2-4ad3-4e97-5a7b-
08d8db1aac26","code":"666666","name":"test6","price":6,"category":"test6","orrderItems":"320d57eb-
3333-45d2-f497-08d8d66a0d39"},"quality":1}"
ValueKind = Object : "{"product":{"id":"72ae28f2-4ad3-4e97-5a7b-
08d8db1aac26","code":"666666","name":"test6","price":6,"category":"test6","orrderItems":"320d57eb-
3333-45d2-f497-08d8d66a0d39"},"quality":1}"
I created a class.
public class OrderR
{
public Guid ID { get; set; }
public Guid orrderItems { get; set; }
public string CODE { get; set; }
public string NAME { get; set; }
public int PRICE { get; set; }
public string CATEGORY { get; set; }
}
I am trying to get an array.
[HttpPost]
public async Task<IActionResult> AddOrder(OrderR[] orderR)
But get null.
What am I doing wrong?
How is it correct?
Create new class:
public class Order
{
public OrderR Product { get; set; }
public int Quality { get; set; }
}
and change your action to this:
[HttpPost]
public async Task<IActionResult> AddOrder(Order[] orders)
{
.... your code
}
it was tested in Postman using this data:
[
{"product":{"id":"72ae28f2-4ad3-4e97-5a7b-08d8db1aac26","code":"666666","name":"test1","price":6,"category":"test6","orrderItems":"320d57eb-3333-45d2-f497-08d8d66a0d39"},"quality":1},
{"product":{"id":"72ae28f2-4ad3-4e97-5a7b-08d8db1aac26","code":"666666","name":"test2","price":6,"category":"test6","orrderItems":"320d57eb-3333-45d2-f497-08d8d66a0d39"},"quality":1},
{"product":{"id":"72ae28f2-4ad3-4e97-5a7b-08d8db1aac26","code":"666666","name":"test3","price":6,"category":"test6","orrderItems":"320d57eb-3333-45d2-f497-08d8d66a0d39"},"quality":1}
]
and everything works fine. If you want to test it in Postman too, add [FromBody] to the action input parameter:
[HttpPost]
public async Task<IActionResult> AddOrder([FromBody] Order[] orders)
{
return Ok(orders);
}
Related
I have a model class called ClientPackage and in my controller action method i receive a FormCollection from an ajax post call that i would like to convert it to the model class ClientPackage.
public class ClientPackage
{
public int DemandeId { get; set; }
public string NumeroRequette { get; set; }
public string NumeroModification { get; set; }
public int CasId { get; set; }
public string NumeroDossier { get; set; }
public string NomPatient { get; set; }
public string PrenomPatient { get; set; }
public string NiveauPriorite { get; set; }
public int NiveauPrioriteId { get; set; }
public Unite UniteDepart { get; set; }
public Unite UniteDestination { get; set; }
public Demandeur DemandeurDepart { get; set; }
public Demandeur DemandeurDestination { get; set; }
public ConditionTransport ConditionTransport { get; set; }
public Transport Transport { get; set; }
}
[HttpPost]
public string AjaxCall(FormCollection formData)
{
ClientPackage package = (ClientPackage)formData; //exception error
}
I would appriciate any help
Instead of trying to convert you can use the FromForm attribute and receive your model as a parameter.
[HttpPost]
public ActionResult CreateClientPackage([FromForm] ClientPackage clientPackage)
{
...
}
Here is how I post models with ajax.
<script>
function PostForm() {
var model = $('#your_form_id').serialize();
$.ajax({
url: '/YourController/AjaxCall',
type: 'POST',
data: model,
success: function (data) {
},
error: function (request, error) {
console.log("Request: " + JSON.stringify(request));
}
});
}
</script>
and in your controller.
[HttpPost]
public string AjaxCall(ClientPackage model)
{
//no need to cast the model to a ClientPackage
//ASP.NET mvc will do it for you as long as you send a serialized form that represents a ClientPackage object
}
Hope this helps!
Model:
[DataContract]
public class Employee
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[DataMember(Name ="id")]
public int Id{ get; set; }
[DataMember(Name = "fullName")]
public string FullName { get; set; }
}
[DataContract]
public class Department
{
public Department()
{
this.Employees = new List<Employee>();
}
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "employees")]
public List<Employee> Employees { get; set; }
}
Controller
public HttpResponseMessage Get([FromUri]Department model)
{
if (ModelState.IsValid)
{
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
Url : "http://localhost:2070/home/get/?id=1&name=IT&Employees=1,John"
I am trying to invoke above URL and the Model does not read the Employees. Other property like int,double,string,decimal are read by the Model.
Can anyone help me on what is the correct format in passing List thru Url.
Also, I dont want to decorate each of my class with modelbinders nor the parameter in my controller.
Tech : WebApi, .Net3.5
You need to specify the index of the list and property to bind with when using FromUri and list/array
Try it this way
http://localhost:2070/home/get/?id=1&name=IT&Employees[0].Id=1&Employees[0].Name=John
I have defined a method defined in AppService file, Signature of method is public PagedResultDto<FetchData> GetSearchData(FetchDataInput searchInput). I'm calling this method from Angular code, but service-proxoes.ts file has generated method in which I need to pass all the parameters one by one.
public class FetchDataInput: PagedAndSortedInputDto, IShouldNormalize
{
public int DataLevel { get; set; }
public int DataType { get; set; }
public string DataCode { get; set; }
public string DescLong { get; set; }
public string LanguageCode { get; set; }
public string DataParent { get; set; }
public void Normalize()
{
if (string.IsNullOrEmpty(Sorting))
{
Sorting = "DataCode";
}
}
}
Service-Proxies.ts file:
getSearchData(dataLevel: number, dataType: number, dataCode: string, descLong: string, languageCode: string, dataParent: string, sorting: string, maxResultCount: number, skipCount: number): Observable<PagedResultDtoOfFetchData> {
So I have to call the getSearchData method by the following way.
this._dataService.getSearchData(AppConsts.dataLevelType, undefined, undefined,
undefined, this.currentLanguage.name, undefined, undefined, undefined, undefined).subscribe((result) => {
//result.items;
});
So I have to pass all the parameters, but if let's say there are 100 parameters, it will be error prone and not good programming style. So it has to take a class object that's it. So is there any way to do the this?
You can create a object to store those parametter like this:
public class FetchDataInput: PagedAndSortedInputDto, IShouldNormalize
{
public SearchModel searchModel{get; set;}
public void Normalize()
{
if (string.IsNullOrEmpty(Sorting))
{
Sorting = "DataCode";
}
}
}
public class SearchModel
{
public int DataLevel { get; set; }
public int DataType { get; set; }
public string DataCode { get; set; }
public string DescLong { get; set; }
public string LanguageCode { get; set; }
public string DataParent { get; set; }
}
...And in the getSearchData, tried to serialize the model and pass it to your api:
_$SearchModelForm= _modalManager.getModal().find('form[name=SearchForm]');
var searchModel = _$SearchModelForm.serializeFormToObject();
this._dataService.getSearchData(searchModel);
after looking for an answer in the already existing questions, I am still a little confused as how I should proceed. I am new to the MVC 3 framework, so if I come off sounding like a dope, I appologize!!
Ok, so I created a MVC 3 internet application, created 3 new Users administrator, user1, and user2. I have created a new model, and controller for my "Posts" I am able to add, edit and delete the items. I currently have a column called UserID in my posts table. I would like this to be automagically populated with the current UsersID. I think I would define this in the controller like this:
[HttpPost]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
public int User = System.Web.Security.Membership.GetUser(id);
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
Inside the model, this is what I currently have:
public class Post
{
public int PostID { get; set; }
public int UserID { get; set; }
public string PostTitle { get; set; }
public int PostType { get; set; }
public string PostBody { get; set; }
public string PostBlogTitle { get; set; }
public string PostBlogURL { get; set; }
public string PostCategory { get; set; }
public string PostSEO { get; set; }
public int PostStatus { get; set; }
}
public class PostDBContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
I would like to replace public int UserID { get; set; } with my newly defined variable in the controller, but not sure where/how to add it.
Not sure I'm clear on what you're trying to achieve. Are you just trying to assign the current user to the model, save it and then pass it back to the view?
If so you can just do this:
[HttpPost]
public ActionResult Create(Post post)
{
if (ModelState.IsValid)
{
// Note: I'm assuming this actually works/returns an int
public int User = System.Web.Security.Membership.GetUser(id);
post.UserID = User;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(post);
}
I have this model:
public class ReservationViewModel
{
public Flight InboundFlight { get; set; }
public Flight OutboundFlight { get; set; }
}
//Flight
public class Flight
{
public List<ISeat> Seats { get; set; }
}
//Seats
public interface ISeat
{
ECabin Cabin { get; }
int NumberOfSeatsAvailable { get; }
int SeatsChosen { get; set; }
string PropertyName { get; }
}
My HTML consist of the folliwing:
<select id="OutboundFlight__0__Seats_SeatsChosen" name="OutboundFlight.[0].Seats.SeatsChosen" class="valid"><option...
<select id="OutboundFlight__0__Seats_SeatsChosen" name="OutboundFlight.[1].Seats.SeatsChosen" class="valid"><option...
<select id="OutboundFlight__0__Seats_SeatsChosen" name="OutboundFlight.[2].Seats.SeatsChosen" class="valid"><option...
My Action:
[HttpPost]
public ActionResult Index(ReservationViewModel model, FormCollection form)
{
return View();
}
Upon submit I try to bind back to the model but the Seats of each flight returns null...
Help will be appreciated
The HTML being generated is incorrect to get it to bind to a list - the field name has to match what what accessing the property from c# would look like:
This should work:
name="OutboundFlight.Seats[0].SeatsChosen"