开发者

Asp.Net MVC 3 ModelBinding Arrays

开发者 https://www.devze.com 2023-04-12 14:02 出处:网络
I am posting something that looks like this: FavoritePerson: \"Dennis\" FavoriteAnimals: [{Type=\"Bear\", Name=\"Bruno\"}, {Type=\"Shark\", Name=\"Sammy\"}, ...]

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 开发者_StackOverflow社区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
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号