2011-06-26 99 views
1

如何從foreach循環中的TextBoxFor幫助程序中檢索數據?我的意思是:在foreach循環中的c#razor mvc 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; } 

回答

1

您應該能夠通過使用在動作的ModelBinder

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

在哪裏name是由Html.TextBoxFor()自動給予文本框的名稱。


編輯

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

:如果您希望將參數名稱從name更改爲更具描述性的,你可以通過使用Html.TextBox,儘管四通打字的損失達到這個然後在你的控制器動作:

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

如果我將模型作爲參數傳遞,該怎麼辦?我的意思是,如果控制器是這樣的:public ActionResult(MyModel model),我從模型中獲取值? – Shaokan

+0

只要你有'string [] Name {get;組; }'對你的模型,默認的ModelBinder仍然能夠綁定到它。 – aligray

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

}