1

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.

4

2 回答 2

5

您是否尝试过使用传递给控制器​​方法的 FormCollection 对象?

[HttpPost]
public ActionResult Index(FormCollection formCollection)
{
  foreach (string extendedProperty in formCollection)
  {
     if (extendedProperty.Contains("Property-"))
     {
       string extendedPropertyValue = formCollection[extendedProperty];
     }
  }

  ...
}

我会尝试遍历该集合中的项目。

于 2013-07-08T18:34:11.927 回答
2

假设您有以下内容Model(我更喜欢ViewModel):

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; }
}

您可以使用如下标记将此模型绑定到视图:

@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" />  
}

最后,您的操作:

[HttpPost]
public ActionResult YourAction(MyModel model)
{
  //simply retrieve model.Properties[0]
  //...
}
于 2013-07-08T19:30:24.977 回答