Reputation: 2941
I am creating API in which has following url
/api/abc/?q=1&a=2&b=3&b=4
^^^^^^^
Input.cs(class used in ModelBinding)
...
public string A { get; set; }
public string B { get; set; }
public string Q { get; set; }
...
I am using default ModelBinding of .NET, But problem with that is when I passed above url, following values are assigned to the property
obj.A = "2" // here obj is object of Input class
obj.B = "3"
obj.Q = "1"
I am expecting obj.B = "3,4"
(when I am doing Request.QueryString["b"], it giving output as "3,4"), but it is binding the first value only.
Why is this happening?(I don't know internals of default ModelBinding but I am guessing it somewhere using Request.QueryString for binding).
Can anyone tell me why it is happening and How can I get "3,4" as obj.B value?
My approach for getting "3,4" for B is
using custom Model Binder I have done following
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
object model = base.BindModel(controllerContext, bindingContext);
var obj = model as Input;
obj.B = Request.QueryString["b"];
}
Upvotes: 1
Views: 39
Reputation:
You are sending multiple values for B
which means that you need to make B
a collection. Note the DefaultModelBinder
binds the first matching name/value pair and ignores the rest if your property is not IEnumerable
.
Change the property to
public IEnumerable<string> B { get; set; }
and it will contain both values (if you then actually want 3,4
, you can use String.Join
on the array).
Upvotes: 2