1

how is it possible to retrieve data from TextBoxFor helper within a foreach loop? I mean:

in the view:

foreach(Language l in ViewBag.Languages){
    <td>@l.lang</td>
    <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; }

2 Answers 2

1

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)
{
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

what if I am passing a model as a parameter? I mean, if the controller is like this: public ActionResult(MyModel model) and I am getting the values from the model?
As long as you have string[] Name { get; set; } on you model, the default ModelBinder will still be able to bind to it.
1
@foreach (var _item in Model.ListSurvey)
{
    @Html.TextBoxFor(m=>m.Question, new { Value = @_item.Question })

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.