Get post data with unknown number of variables in ASP MVC

元气小坏坏 提交于 2021-01-28 11:43:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!