Shaokan Shaokan - 1 year ago 221
C# Question

c# razor mvc textboxfor in foreach loop

how is it possible to retrieve data from

helper within a foreach loop? I mean:

in the view:

foreach(Language l in ViewBag.Languages){
<td>@Html.TextBoxFor(model => model.Name)

and how can I retrieve it in the controller once posted?

MyModel.Name //this returns the value of the first textbox within the foreach loop

By the way model.Name is defined in MyModel.cs as:

public string Name { get; set; }

Answer Source

You should be able to use the ModelBinder in your action by using:

public ActionResult MyAction(string[] name)
    foreach (var item in name)
        // Process items

Where name is the name automatically given to the text-boxes by Html.TextBoxFor().

Edit: If you wish to change the parameter name from name to something more descriptive, you can achieve this by using Html.TextBox, albeit with a loss of stong-typing:

@Html.TextBox("SomeMoreDescriptiveName", Model.Name);

And then in your controller action:

public ActionResult MyAction(string[] SomeMoreDescriptiveName)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download