Asp.Net MVC 3 ModelBinding Arrays - asp.net-mvc-3

I am posting something that looks like this:
FavoritePerson: "Dennis"
FavoriteAnimals: [{Type="Bear", Name="Bruno"}, {Type="Shark", Name="Sammy"}, ...]
Is there some shape for the Model to be that the DefaultModelBinder would be able to handle this? Something like
class FavoriteAnimalSubmission {
string Type {get; set;}
string Name {get; set;}
}
[HttpPost]
public MarkFavorites(string favoritePerson, FavoriteAnimalSubmission[] favoriteAnimals[]) {
...
}
Will fill favoritePerson and favoriteAnimals.Count but not the properties on each animal.

There is nothing out of the box that will handle a mixture of JSON (which in your case is invalid) and standard url encoded parameters. You will have to write a custom model binder if you ever needed to handle this request. Or simply modify your request to:
{
"FavoriteAnimals": [
{
"Type": "Bear",
"Name": "Bruno"
},
{
"Type": "Shark",
"Name": "Sammy"
}
],
"FavoritePerson": "Dennis"
}
and then on the server:
public class MyViewModel
{
public string FavoritePerson { get; set; }
public FavoriteAnimalSubmission[] FavoriteAnimals { get; set; }
}
public class FavoriteAnimalSubmission
{
public string Type { get; set; }
public string Name { get; set; }
}
and your controller action:
[HttpPost]
public MarkFavorites(MyViewModel model)
{
...
}
and the AJAX request to invoke it:
var model =
{
"FavoriteAnimals": [
{
"Type": "Bear",
"Name": "Bruno"
},
{
"Type": "Shark",
"Name": "Sammy"
}
],
"FavoritePerson": "Dennis"
};
$.ajax({
url: '#Url.Action("MarkFavorites", "SomeController")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(model),
success: function(result) {
// do something with the result
}
});

Related

{"$":["'i' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],"request":["The request field is required."]}}

I'm simply trying to send this AJAX request to my controller but keep ending up with the error in the title, Everything works fine on swagger API so I'm assuming somehow I'm passing the data wrong on the ajax request? here is the request:
function submitForm(){
var fullName = $("#name").find(":selected").val();
console.log(fullName);
var firstName = fullName.split(' ').slice(0, -1).join(' ');
console.log(firstName);
var lastName = fullName.split(' ').slice(-1).join(' ');
console.log(lastName);
console.log($("#name").find(":selected").attr("name"));
var formData = {
id: null,
type: 2,
person: $("#name").find(":selected").attr("name"),
firstName: firstName,
lastName: lastName,
dateCreated: new Date().toISOString(),
dateModified: new Date().toISOString(),
modifiedBy: "Web Application"
};
console.log(formData);
$.ajax({
type: "POST",
url: 'https://localhost:44398/api/Attendee1/InsertAttendee',
data: formData,
contentType: 'application/json',
success: function(res){
console.log(res)
}
});
}
Here is my Controller
[HttpPost("InsertAttendee")]
public async Task<ActionResult<Attendee2>> InsertAttendee(Attendee2 request, CancellationToken cancellationToken)
{
Attendee2 Attendee2 = new Attendee2();
Attendee2.Type = request.Type;
Attendee2.Person = request.Person;
Attendee2.FirstName = request.FirstName;
Attendee2.LastName = request.LastName;
Attendee2.DateCreated = request.DateCreated;
Attendee2.DateModified = request.DateModified;
Attendee2.ModifiedBy = request.ModifiedBy;
var returnedId = new OutputParameter<int?>();
try
{
await _context.GetProcedures().InsertAttendeeAsync(Attendee2.DateCreated, Attendee2.DateModified, Attendee2.FirstName, Attendee2.LastName, Attendee2.ModifiedBy, Attendee2.Person, Attendee2.Type, returnedId, null, cancellationToken);
}
catch(Exception ex)
{
return StatusCode(500, ex);
}
return CreatedAtAction("GetAttendee1", new { id = Attendee2.Id }, Attendee2);
}
Attendee 2 Model
public class Attendee2
{
[Key]
public int Id { get; set; }
public int Type { get; set; }
public int? Person { get; set; }
[StringLength(100)]
[Unicode(false)]
public string FirstName { get; set; }
[StringLength(100)]
[Unicode(false)]
public string LastName { get; set; }
[Column(TypeName = "datetime")]
public DateTime DateCreated { get; set; }
[Column(TypeName = "datetime")]
public DateTime DateModified { get; set; }
[Required]
[StringLength(50)]
[Unicode(false)]
public string ModifiedBy { get; set; }
}
Full Error: {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-f5e0489cf9bb95269b878874ccb4e152-3003e7f9f1a70d1d-00","errors":{"$":["'i' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],"request":["The request field is required."]}}
The Solution was to JSON.Stringify(formData).

MongoDB search nested objects in an array

I am using MongoDB to store all the events in my Eventbrite clone. So I have a collection called events then the objects in this collection consists of their name and and array of users that have rsvp to the event. I can query for any events that the current user has created but unable to figure out how to query both events the user has created and rsvp to.
Here is the compiled query that I am using to try to get all the users events.
events.find({"$and":[{"user_id":"5d335704802df000076bad97"},{"user_id":{"$ne":null}}],"$or":[{"checkins.user_id":"5d335704802df000076bad97"}]},{"typeMap":{"root":"array","document":"array"}})
I am using the Laravel MongoDB plugin to query my data in php it looks like this
$user->events()->orWhere(function ($query) use ($user){
return $query->where('checkins.user_id',new ObjectID($user->id));
})->get()
The event object looks something like this:
{
"name": "test",
"user_id": "1"
"rsvp": [
{"user_id": "12"}
]
}
An user can rsvp to other event that are not their own.
you need an $or filter and $elemMatch to get events that belong to a given user or events they've rsvp'd to.
db.events.find({
"$or": [
{
"user_id": "5d33e732e1ea9d0d6834ef3d"
},
{
"rsvp": {
"$elemMatch": {
"user_id": "5d33e732e1ea9d0d6834ef3d"
}
}
}
]
})
unfortunately i can't help you with laravel version of the query. in case it helps, below is the c# code that generated the above mongo query.
using MongoDB.Entities;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class user : Entity
{
public string name { get; set; }
}
public class Event : Entity
{
public string name { get; set; }
public string user_id { get; set; }
public rsvp[] rsvp { get; set; }
}
public class rsvp
{
public string user_id { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
var mike = new user { name = "mike" };
var dave = new user { name = "dave" };
mike.Save();
dave.Save();
(new[] {
new Event
{
name = "mike's event",
user_id = mike.ID,
rsvp = new[]
{
new rsvp { user_id = dave.ID }
}
},
new Event
{
name = "dave's event",
user_id = dave.ID,
rsvp = new[]
{
new rsvp { user_id = mike.ID }
}
}
}).Save();
var result = DB.Find<Event>()
.Many(e =>
e.user_id == mike.ID ||
e.rsvp.Any(r => r.user_id == mike.ID));
}
}
}

Extra items in JSON data when using Web API

I have a problem with the JSON data from the Web API service.
In a regular Web API Controller, I get the result given below.
[
{
"title": "başlık",
"description": "Tanımlama",
"creationTime": "2018-01-15T17:20:06.9801797",
"state": 0,
"assignedPersonId": "afd46520-521d-4945-a4ee-083893e1d14c",
"assignedPersonName": "derya",
"id": 2
},
{
"title": "title",
"description": "description",
"creationTime": "2018-01-15T17:17:26.5161288",
"state": 0,
"assignedPersonId": null,
"assignedPersonName": null,
"id": 1
}
]
But when using ASP.NET Boilerplate infrastructure, I get the same data as:
{
"result": {
"items": [
{
"title": "başlık",
"description": "Tanımlama",
"creationTime": "2018-01-15T17:20:06.9801797",
"state": 0,
"assignedPersonId": "afd46520-521d-4945-a4ee-083893e1d14c",
"assignedPersonName": "derya",
"id": 2
},
{
"title": "title",
"description": "description",
"creationTime": "2018-01-15T17:17:26.5161288",
"state": 0,
"assignedPersonId": null,
"assignedPersonName": null,
"id": 1
}
]
},
"targetUrl": null,
"success": true,
"error": null,
"unAuthorizedRequest": false,
"__abp": true
}
It seems that the actual raw data is nested in an outer data structure. Because of this, deserialization like below doesn't work.
List<Class1> data = JsonConvert.DeserializeObject<List<Class1>>(JSONString);
And I have to manage some string operations on JSONString.
Am I doing something wrong? Thanks in advance.
From the documentation on WrapResult and DontWrapResult Attributes:
You can control wrapping using WrapResult and DontWrapResult attributes for an action or all actions of a controller.
ASP.NET MVC Controllers
ASP.NET Boilerplate wraps ASP.NET MVC action results by default if return type is JsonResult (or Task<JsonResult> for async actions). You can change this by using WrapResult attribute as shown below:
public class PeopleController : AbpController
{
[HttpPost]
[WrapResult(WrapOnSuccess = false, WrapOnError = false)]
public JsonResult SavePerson(SavePersonModel person)
{
// TODO: save new person to database and return new person's id
return Json(new {PersonId = 42});
}
}
As a shortcut, we can just use [DontWrapResult] which is identical for this example.
You can change this default behaviour from startup configuration.
This applies not only to ASP.NET MVC Controllers, but also to ASP.NET Web API Controllers, Dynamic Web API Layer and ASP.NET Core Controllers.
Thanks, #Aaron for such a wonderful clean answer.
#Inanc, If you can map this JSON response with the below-mentioned class also.
JSON:
{
"result": {
"items": [
{
"title": "başlık",
"description": "Tanımlama",
"creationTime": "2018-01-15T17:20:06.9801797",
"state": 0,
"assignedPersonId": "afd46520-521d-4945-a4ee-083893e1d14c",
"assignedPersonName": "derya",
"id": 2
},
{
"title": "title",
"description": "description",
"creationTime": "2018-01-15T17:17:26.5161288",
"state": 0,
"assignedPersonId": null,
"assignedPersonName": null,
"id": 1
}
]
},
"targetUrl": null,
"success": true,
"error": null,
"unAuthorizedRequest": false,
"__abp": true
}
Code:
public class Item
{
public string title { get; set; }
public string description { get; set; }
public DateTime creationTime { get; set; }
public int state { get; set; }
public string assignedPersonId { get; set; }
public string assignedPersonName { get; set; }
public int id { get; set; }
}
public class Result
{
public List<Item> items { get; set; }
}
public class RootObject
{
public Result result { get; set; }
public object targetUrl { get; set; }
public bool success { get; set; }
public object error { get; set; }
public bool unAuthorizedRequest { get; set; }
public bool __abp { get; set; }
}
Deserialization Code:
List<RootObject> data = JsonConvert.DeserializeObject<List<RootObject>>(JSONString);
Add these two lines to the PreInitialize() method of your Web.Core project module (<ProjectName>WebCoreModuleModule.cs): docs
Configuration.Modules.AbpAspNetCore().DefaultWrapResultAttribute.WrapOnError = false;
Configuration.Modules.AbpAspNetCore().DefaultWrapResultAttribute.WrapOnSuccess = false;

How to parse _data to an array?

I have an API like this:
public class Calendar : FullAuditedEntity
{
public string EventName { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
public List<Calendar> GetCalendar()
{
var result = _calendarRepository.GetAll().ToList();
return new List<Calendar>(result.MapTo<List<Calendar>>());
}
I can call to this API successfully from view and returned data in Swagger:
var _$calendarService = abp.services.myproject.calendar;
var _data = _$calendarService.getCalendar();
Here is the value of _data:
Object { resolve: Deferred/</e[f[0]](), resolveWith: fireWith(a, c), reject: Deferred/</e[f[0]](), rejectWith: fireWith(a, c), notify: Deferred/</e[f[0]](), notifyWith: fireWith(a, c), state: state(), always: always(), then: then(), promise: promise(a), 4 more… }
So how can I parse this _data to an array to use (not jTable)
getCalendar is a jquery.ajax call that returns jqXHR.
_$calendarService.getCalendar().done(function (data, textStatus, jqXHR) {
var items = data.items;
var totalCount = data.totalCount;
// ...
});

Populating child drop down based on what was selected from parent drop down list

I am using the latest version of jQuery and ASP.NET MVC 3 with the Razor view engine.
I have tried Google looking for a decent example of loading a child drop down list when a parent drop down item is selected. I am looking to do this via jQuery AJAX using JSON. My knowledge of this is zero.
I have a Category class with a list of categories. It's a parent-child association.
If I select a category from the parent drop down list, then all the child categories need to be listed in the child drop down list for the selected parent category.
This is what I currently have, but need to complete it, not sure if I am in the right direction:
$(document).ready(function () {
$('#ddlParentCategories').change(function () {
alert('changed');
});
});
I loaded my drop down list from my view model as such:
#Html.DropDownListFor(x => x.ParentCategoryId, new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId), "-- Select --", new { id = "ddlParentCategories" })
The first item has text "-- Select --" (for both parent and child drop down lists). On initial page load nothing must be loaded in the child drop down list. When a value is selected then the child drop down list must be populated. And when "-- Select --" is selected again in the parent drop down list then all the items in the child drop down list must cleared except "-- Select --".
If possible, if the child categories is loading, how do I display that "round" loading icon?
UPDATE
I have updated my code to Darin's code, and I cannot get it to work properly:
Category class:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public bool IsActive { get; set; }
public int? ParentCategoryId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
EditProductViewModel class:
public class EditProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
public bool IsActive { get; set; }
public string PageTitle { get; set; }
public bool OverridePageTitle { get; set; }
public string MetaKeywords { get; set; }
public string MetaDescription { get; set; }
public int ParentCategoryId { get; set; }
public IEnumerable<Category> ParentCategories { get; set; }
public int ChildCategoryId { get; set; }
public IEnumerable<Category> ChildCategories { get; set; }
}
ProductController class:
public ActionResult Create()
{
EditProductViewModel viewModel = new EditProductViewModel
{
ParentCategories = categoryService.GetParentCategories()
.Where(x => x.IsActive)
.OrderBy(x => x.Name),
ChildCategories = Enumerable.Empty<Category>(),
IsActive = true
};
return View(viewModel);
}
public ActionResult AjaxBindingChildCategories(int parentCategoryId)
{
IEnumerable<Category> childCategoryList = categoryService.GetChildCategoriesByParentCategoryId(parentCategoryId);
return Json(childCategoryList, JsonRequestBehavior.AllowGet);
}
Create view:
<tr>
<td><label>Parent Category:</label> <span class="red">*</span></td>
<td>#Html.DropDownListFor(x => x.ParentCategoryId,
new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId),
"-- Select --",
new { data_url = Url.Action("AjaxBindingChildCategories"), id = "ParentCategories" }
)
#Html.ValidationMessageFor(x => x.ParentCategoryId)
</td>
</tr>
<tr>
<td><label>Child Category:</label> <span class="red">*</span></td>
<td>#Html.DropDownListFor(x => x.ChildCategoryId,
new SelectList(Model.ChildCategories, "Id", "Name", Model.ChildCategoryId),
"-- Select --",
new { id = "ChildCategories" }
)
#Html.ValidationMessageFor(x => x.ChildCategoryId)
</td>
</tr>
<script type="text/javascript">
$(document).ready(function () {
$('#ParentCategories').change(function () {
var url = $(this).data('url');
var data = { parentCategoryId: $(this).val() };
$.getJSON(url, data, function (childCategories) {
var childCategoriesDdl = $('#ChildCategories');
childCategoriesDdl.empty();
$.each(childCategories, function (index, childCategory) {
childCategoriesDdl.append($('<option/>', {
value: childCategory, text: childCategory
}));
});
});
});
});
</script>
It goes into my AjaxBindingChildCategories action and it brings back records, it just doesn't want to display my child category dropdownlist. I had a look in Fire Bug and the error that I get is:
GET AjaxBindingChildCategories?parentCategoryId=1
500 Internal Server Error
Here's an example of cascading drop down lists. As always start by defining a view model:
public class MyViewModel
{
[DisplayName("Country")]
[Required]
public string CountryCode { get; set; }
public IEnumerable<SelectListItem> Countries { get; set; }
public string City { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// TODO: Fetch countries from somewhere
Countries = new[]
{
new SelectListItem { Value = "FR", Text = "France" },
new SelectListItem { Value = "US", Text = "USA" },
},
// initially we set the cities ddl to empty
Cities = Enumerable.Empty<SelectListItem>()
};
return View(model);
}
public ActionResult Cities(string countryCode)
{
// TODO: based on the selected country return the cities:
var cities = new[]
{
"Paris", "Marseille", "Lyon"
};
return Json(cities, JsonRequestBehavior.AllowGet);
}
}
a view:
#model MyViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.CountryCode)
#Html.DropDownListFor(
x => x.CountryCode,
Model.Countries,
"-- Select country --",
new { data_url = Url.Action("cities") }
)
#Html.ValidationMessageFor(x => x.CountryCode)
</div>
<div>
#Html.LabelFor(x => x.City)
#Html.DropDownListFor(
x => x.City,
Model.Cities,
"-- Select city --"
)
#Html.ValidationMessageFor(x => x.City)
</div>
<p><input type="submit" value="OK" /></p>
}
and finally the unobtrusive javascript in a separate file:
$(function () {
$('#CountryCode').change(function () {
var url = $(this).data('url');
var data = { countryCode: $(this).val() };
$.getJSON(url, data, function (cities) {
var citiesDdl = $('#City');
citiesDdl.empty();
$.each(cities, function (index, city) {
citiesDdl.append($('<option/>', {
value: city,
text: city
}));
});
});
});
});
jQuery script will look like this:
<script type="text/javascript">
function getCities(abbr) {
$.ajax({
url: "#Url.Action("Cities", "Locations")",
data: {abbreviation: abbr},
dataType: "json",
type: "POST",
error: function() {
alert("An error occurred.");
},
success: function(data) {
var items = "";
$.each(data, function(i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#City").html(items);
}
});
}
$(document).ready(function(){
$("#State").change(function() {
var abbr = $("#State").val();
getCities(abbr);
});
});
</script>
A repository to retrieve data could look like this (obviously hook it up to live data though):
public class LocationRepository : ILocationRepository
{
public IQueryable<State> GetStates()
{
return new List<State>
{
new State { Abbreviation = "NE", Name = "Nebraska" },
new State { Abbreviation = "NC", Name = "North Carolina" }
}.AsQueryable();
}
public IQueryable<City> GetCities(string abbreviation)
{
var cities = new List<City>();
if (abbreviation == "NE")
{
cities.AddRange(new List<City> {
new City { Id = 1, Name = "Omaha" },
new City { Id = 2, Name = "Lincoln" }
});
}
else if (abbreviation == "NC")
{
cities.AddRange(new List<City> {
new City { Id = 3, Name = "Charlotte" },
new City { Id = 4, Name = "Raleigh" }
});
}
return cities.AsQueryable();
}
}
public interface ILocationRepository
{
IQueryable<State> GetStates();
IQueryable<City> GetCities(string abbreviation);
}
Controllers could look like this:
public class LocationsController : Controller
{
private ILocationRepository locationRepository = new LocationRepository();
[HttpPost]
public ActionResult States()
{
var states = locationRepository.GetStates();
return Json(new SelectList(state, "Id", "Name"));
}
[HttpPost]
public ActionResult Cities(string abbreviation)
{
var cities = locationRepository.GetCities(abbreviation);
return Json(new SelectList(cities, "Abbreviation", "Name"));
}
}
I am assuming you populate the parent dropdown from server side and also the first option in this parent dd is "--- Select ---"
You can try this
$(document).ready(function () {
var $parent = $('#ddlParentCategories');
var $child = $('#ddlChildCategories');
$child.find("option:gt(0)").remove();
if(!$parent.children().eq(0).is(":selected")){
$parent.change(function () {
$.ajax({
url: "urlToFetchTheChild",
data: { categoryId: this.value },
success: function(data){
//The data you send should be a well formed array of json object containing code/value pair of child categories
for(var i = 0;i<data.length;i++){
$child.append("<option value='"+ data[i].code +"'>"+ data[i].value +"</option>");
}
}
});
});
}
});

Resources