2

How to solve this case?

Request: http://example.com/test?geoPoints[0][Latitude]=123&geoPoints[0][Longitude]=1

My controller action:

[HttpGet]
public HttpResponseMessage Test([FromUri] List<GeoPoint> geoPoints)

With request http://example.com/test?geoPoints[0].Latitude=123&geoPoints[0].Longitude=1 is ok, but I need to solve the first case.

Please help.

I'm sorry, my English is not good.

3
  • What technology is that? Please - tag your question accordingly. Commented May 10, 2015 at 18:40
  • I´m sory. ASP.NET .net framework 4.5.1 Commented May 10, 2015 at 19:20
  • You can't unless you create a custom ModelBinder Commented May 10, 2015 at 22:18

1 Answer 1

1

You can create a custom ModelBinder like this(just for the reference):

public class GeoPointModelBinder : IModelBinder
{
    public static Regex regex = new Regex(@"^geoPoints\[\(d+)\]\[(longitude|latitude)\]$", RegexOptions.IgnoreCase);

    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var query = actionContext.Request.RequestUri.Query;

        var parameters = query
            .Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(it => it.Split('='))
            .Where(it => regex.IsMatch(it[0]))
            .ToDictionary(it => it[0], it => it[1]);

        var points = parameters
            .Select(it => new GeoPoint())
            .ToList();

        foreach (var parameter in parameters)
        {
            var match = regex.Match(parameter.Key);
            var firstGroup = match.Groups[1];
            var secondGroup = match.Groups[2];

            int index = int.Parse(firstGroup.Value);
            string field = secondGroup.Value;

            if (string.Equals(field, "latitude", StringComparison.OrdinalIgnoreCase))
            {
                points[index].Latitude = parameter.Value;
            }
            else
            {
                points[index].Longitude = parameter.Value;
            }
        }

        bindingContext.Model = points;
        return true;
    }
}
...

[HttpGet]
public HttpResponseMessage Test([ModelBinder(typeof(GeoPointModelBinder))]List<GeoPoint> geoPoints) 
{ 
   //... 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.