1

I generate a number of textbox based on the number of element in a list.

The model :

public class MyModel
{
    public List<Language> Languages { get; set; }
    public string  Code { get; set; }
}

public class Language
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public bool IsDefault { get; set; }
}

The view :

@model MyModel

<form id="formDetail">
@Html.TextBoxFor(m => m.Code)
@foreach (var item in Model.Language)
{   
    <input type="text" id="@item.Code"/> //the code are : FR, EN, GE, ...
}
</form>

I post the form (POST) with Ajax.

Controller :

[HttpPost]
public ActionResult Save(MyModel myModel)
{
..
}

The number of textbox can be different depending of the number of language in the Language list. Could you tell me how get the value of these textboxes in the controller

Thanks,

1
  • can you add js post method? Commented May 13, 2013 at 15:41

2 Answers 2

3

Replace:

@foreach (var item in Model.Language)
{   
    <input type="text" id="@item.Code"/> //the code are : FR, EN, GE, ...
}

with:

@for (var i = 0; i < Model.Language.Count; i++)
{   
    @Html.HiddenFor(x => x.Language[i].Id)
    @Html.HiddenFor(x => x.Language[i].Name)
    @Html.HiddenFor(x => x.Language[i].IsDefault)
    @Html.EditorFor(x => x.Language[i].Code)
}

and the model binder's gonna take care for the rest.

Sign up to request clarification or add additional context in comments.

2 Comments

It's not that, my mistake, I rephrase. I have a list with 3 languages, I have to generate for each textbox. The value of these textbox are NOT a value from the language list. A real example, I have to give a name to a product, one name by language. I'd like post these names to the controller.
Then you should have a corresponding List in your view model to bind the textboxes to. And in the action that is rendering this view populate this List property from the Languages collection you have.
1

You have to use an indexed for loop to render the corresponding values for the nameattribute for the inputs, the TextboxFor helper and a hidden field, that sends the value for the Code property:

@for (int i=0; i<Model.Language.Count; i++)
{   
    @Html.TextboxFor(m => Model.Language[i].Name)
    @Html.HiddenFor(m => Model.Language[i].Code)
}

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.