MVC 3模型与下划线绑定

时间:2012-07-23 13:12:20

标签: c# asp.net-mvc json asp.net-mvc-3 model-binding

我发布带有下划线(like_this)的变量名称的json,并尝试绑定到camelcased(LikeThis)的模型,但这些值无法绑定。

我知道我可以编写一个自定义模型绑定器,但由于强调的约定很常见,我希望解决方案已经存在。

我想要发布的动作/模型是:

/* in controller */
[HttpPost]
public ActionResult UpdateArgLevel(UserArgLevelModel model) {
    // do something with the data
}

/* model */
public class UserArgLevelModel {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string Surname { get; set; }
    public int ArgLevelId { get; set; }
}

和json数据类似:

{
    id: 420007,
    first_name: "Marc",
    surname: "Priddes",
    arg_level_id: 4
}

(不幸的是我不能改变json或模型的命名)

1 个答案:

答案 0 :(得分:10)

您可以开始撰写custom Json.NET ContractResolver

public class DeliminatorSeparatedPropertyNamesContractResolver :
    DefaultContractResolver
{
    private readonly string _separator;

    protected DeliminatorSeparatedPropertyNamesContractResolver(char separator)
        : base(true)
    {
        _separator = separator.ToString();
    }

    protected override string ResolvePropertyName(string propertyName)
    {
        var parts = new List<string>();
        var currentWord = new StringBuilder();

        foreach (var c in propertyName)
        {
            if (char.IsUpper(c) && currentWord.Length > 0)
            {
                parts.Add(currentWord.ToString());
                currentWord.Clear();
            }
            currentWord.Append(char.ToLower(c));
        }

        if (currentWord.Length > 0)
        {
            parts.Add(currentWord.ToString());
        }

        return string.Join(_separator, parts.ToArray());
    }
}

这是针对您的具体情况,因为您需要snake case ContractResolver

public class SnakeCasePropertyNamesContractResolver :
    DeliminatorSeparatedPropertyNamesContractResolver
{
    public SnakeCasePropertyNamesContractResolver() : base('_') { }
}

然后你可以编写一个自定义属性来装饰你的控制器动作:

public class JsonFilterAttribute : ActionFilterAttribute
{
    public string Parameter { get; set; }
    public Type JsonDataType { get; set; }
    public JsonSerializerSettings Settings { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {    
        if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
        {
            string inputContent;
            using (var reader = new StreamReader(filterContext.HttpContext.Request.InputStream))
            {
                inputContent = reader.ReadToEnd();
            }

            var result = JsonConvert.DeserializeObject(inputContent, JsonDataType, Settings ?? new JsonSerializerSettings());
            filterContext.ActionParameters[Parameter] = result;
        }
    }
}

最后:

[JsonFilter(Parameter = "model", JsonDataType = typeof(UserArgLevelModel), Settings = new JsonSerializerSettings { ContractResolver = new SnakeCasePropertyNamesContractResolver() })]
public ActionResult UpdateArgLevel(UserArgLevelModel model) {
{
    // model is deserialized correctly!
}