ASP.NET MVC and Web API model binding - how do I bind to properties with names disallowed by the language?

1.4k views Asked by At

An example of basic model binding to an object in ASP.NET MVC or the ASP.NET Web API might look like this (using C# as example):

public class MyModel
{
    public string value1 { get; set; } 
    public string value2 { get; set; }
}

public ValuesController : ApiController
{
    public HttpResponseMessage Post(MyModel model) { ... }
}

As long as the POST body looks like value1=somevalue&value2=someothervalue things map just fine.

But how do I handle a scenario where the post body contains parameter names that are disallowed as class property names, such as body-text=bla&...?

2

There are 2 answers

1
peinearydevelopment On

You should be able to utilize data serialization attributes to help you with this:

[DataContract]
public class MyModel
{
    [DataMember(Name = "body-text")]
    public string value1 { get; set; } 
    public string value2 { get; set; }
}
0
Ben Wilde On

You can force Asp.Net to use the Newtonsoft.JSON deserializer by passing a JObject to your action, although it is a bit annoying to have to do it like this.

Then you can work with it as a JObject or call .ToObject<T>(); which will then honor the JsonProperty attribute.

// POST api/values
public IHttpActionResult Post(JObject content)
{
    var test = content.ToObject<MyModel>();
    // now you have your object with the properties filled according to JsonProperty attributes.
    return Ok();
}

MyModel example:

 public class MyModel
 {
     [JsonProperty(Name = "body-text")]
     public string value1 { get; set; } 

     public string value2 { get; set; }
 }