Reputation: 50728
I have an interesting problem, in my form I have this:
<form class="form-horizontal" role="form" method="post"
action="@Url.Action("Edit", "Data")">
@Html.HiddenFor(i => i.Metadata.Name)
<input name="@Html.NameFor(i => i.RecordKey)" type="hidden" value="@Model.RecordKey" />
I've tried with both the RecordKey field as @Html.HiddenFor, and with the approach above, and for this one I'm getting a value returned as:
string[] { "value" }
It's returning a one value array, not just the string directly. In the model, RecordKey is typed as Object, as it may be an integer in some scenarios, and others a string. Any idea why this is posted back this way? I thought maybe I had dual inputs with this name, but it's not anywhere else in the model...
I had a model defined as:
public class FormModel
{
public object RecordKey { get; set; }
}
And the action that receives it is the following. Once I get the data back, FormModel has a single array and I used the following to convert it.
public ActionResult Edit(FormModel model)
{
if (model.RecordKey is string[])
model.RecordKey = ((string[])model.RecordKey).First();
}
On the client, it's what you would expect:
<input name="RecordKey" type="hidden" value="X"></input>
I'm not quite sure why it's doing that in the first place... No custom model binding is in place...
Upvotes: 1
Views: 2158
Reputation:
This occurs because you have declared you property as typeof object
. The default model binder has no way of knowing if your posting back a value type (string
, int
etc.) or a collection of values so when it first initializes your model it creates an array to allow for all possibilities (and adds the posted values to that array). If you change your property to
public string RecordKey { get; set; }
Then it will be correctly bound as a string
Upvotes: 1