问题
I have an entity with a variable set of attributes named ExtendedProperty, these have a key and a value.
In my html razor view, I have this:
@if (properties.Count > 0)
{
<fieldset>
<legend>Extended Properties</legend>
<table>
@foreach (var prop in properties)
{
<tr>
<td>
<label for="Property-@prop.Name">@prop.Name</label>
</td>
<td>
<input type="text" name="Property-@prop.Name"
value="@prop.Value"/>
</td>
</tr>
}
</table>
</fieldset>
}
How can I access this data on my controller once the user fills it in? Is there a way to do this so that I can use the model bindings instead of manual html?
EDIT = Please note that I'm still using a model, and there are other things in the form that do use things like @Html.EditFor(m => m.prop). But I couldn't find a way to integrate these variable properties in.
Thanks.
回答1:
Let's suppose you have the following Model (ViewModel, I prefer):
public class ExtendedProperties
{
public string Name { get; set; }
public string Value { get; set; }
}
public class MyModel
{
public ExtendedProperties[] Properties { get; set; }
public string Name { get; set; }
public int Id { get; set; }
}
You can bind this model to a view using a markup like:
@using (Html.BeginForm("YourAction", "YourController", FormMethod.Post))
{
<input type="text" name="Name" />
<input type="number" name="Id" />
<input type="text" name="Properties[0].Name" />
<input type="text" name="Properties[0].Value" />
...
<input type="text" name="Properties[n].Name" />
<input type="text" name="Properties[n].Value" />
}
Finally, your action:
[HttpPost]
public ActionResult YourAction(MyModel model)
{
//simply retrieve model.Properties[0]
//...
}
回答2:
Have you tried using the FormCollection object passed to the controller method?
[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
foreach (string extendedProperty in formCollection)
{
if (extendedProperty.Contains("Property-"))
{
string extendedPropertyValue = formCollection[extendedProperty];
}
}
...
}
I would try traversing through the items in that collection.
来源:https://stackoverflow.com/questions/17533450/get-post-data-with-unknown-number-of-variables-in-asp-mvc