在foreach循环中使用c#razor mvc textboxfor

时间:2011-06-26 11:56:52

标签: c# loops view model foreach

如何在foreach循环中从TextBoxFor助手中检索数据?我的意思是:

在视图中:

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

如何在发布后在控制器中检索它?

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

顺便说一句,model.Name在MyModel.cs中定义为:

public string Name { get; set; }

2 个答案:

答案 0 :(得分:1)

您应该可以在操作中使用ModelBinder

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

name是由Html.TextBoxFor()自动赋予文本框的名称。


编辑:如果您希望将参数名称从name更改为更具描述性的内容,则可以使用Html.TextBox来实现此目的,尽管失去了强力 - 打字:

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

然后在你的控制器动作中:

public ActionResult MyAction(string[] SomeMoreDescriptiveName)
{
    ...
}

答案 1 :(得分:1)

@foreach (var _item in Model.ListSurvey)
{
    @Html.TextBoxFor(m=>m.Question, new { Value = @_item.Question })

}