简体   繁体   中英

Can't get JSON from IEnumerable in ASP.NET MVC

The problem is that I can't get proper answer JSON to be parsed from IEnumerable, that is very strange by the reason that I did this many time by automated JSON response from MVC controller.

So here is the class:

public class Error
{
    public Error(string key, string message)
    {
        Key = key;
        Message = message;
    }

    private string Key { get; set; }
    private string Message { get; set; }
}

The extension:

public static class ModelStateHelper
{
    public static IEnumerable<Error> ErrorsDictionary(this ModelStateDictionary modelState)
    {
        if (modelState.IsValid) return null;
        var result = from ms in modelState
            where ms.Value.Errors.Any()
            let fieldKey = ms.Key
            let errors = ms.Value.Errors
            from error in errors
            select new Error(fieldKey, error.ErrorMessage);
        return result;
    }
}

And finally here is controller:

[HttpPost]
public async Task<ActionResult> Add(PermissionsViewModel model)
{
    if (!ModelState.IsValid)
    {
        var errors = ModelState.ErrorsDictionary();
        return Json(new {HttpStatusCode = HttpStatusCode.BadRequest, errors});
    }
    var result = await _ps.Create(model);
    return Json(result);
}

The answer I'm receiving is: "errors":[{},{}]} instead of errors information.

It's because your properties are scoped as private and private properties are not serialized by default in most serialization frameworks(*side note). You can make them public and if you really need to add a private setters. This way the state will be serialized.

public class Error
{
    public Error(string key, string message)
    {
        Key = key;
        Message = message;
    }

    public string Key { get; set; }
    public string Message { get; set; }

    // option 2 is with private setter but commented out
    /*public string Key { get; private set; }
    public string Message { get; private set; }*/
}

  • Side Note ( from above ) - In some frameworks you can specify that it should still serialize private fields. You also don't mention what you are using for JSON serialization so I can't tell you if you can change this behavior in the config or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM