2014-02-13 78 views
0

我有一个HTML开始形式MVC表收集问题

@using (Html.BeginForm("Search", "Reports",FormMethod.Post, new { enctype = "multipart/form-data", @class = "form-inline" })) 
{ 
    <div class="form-group"> 
     <input type="text" class="form-control input-sm" placeholder="Value" name="SearchValue"> 
     <input type="text" class="form-control input-sm second-value" placeholder="Value" style="display:none;" name="SearchValue1"> 
     <button type="button" class="btn btn-default btn-Add">+</button> 

    </div> 
    <div id="othersearch"></div> 
    <input type="submit" value="Search" class="btn btn-primary" /> 
} 

我想在一个控制器来发布这种形式的项目

public ActionResult Search(FormCollection collection) 
{ 
    string searchvalue = collection.Get("SearchValue"); 
    return View(); 
} 

我的问题是,有时第二个文本框是不可见..那时我不想收集values.And当我按下按钮添加生成相同类型的输入字段在窗体中相同的名称(我可以添加许多输入框)。那我怎么收集所有这些在我的控制器中。请帮助我..

回答

5

您的情况下,您可以将所有文本框命名为“SeachValue”。

string searchvalue = collection.Get("SearchValue");

这将返回所有文本框的值作为逗号saperated字符串,那么可以拆分,并进一步使用。

退房的屏幕截图 enter image description here

的HTML

enter image description here

,结果

enter image description here

+0

它在同一行的情况下,按下按钮之后+ 再次生成的总数,我必须收集4个文本框的值 – neel

+0

无论有多少文本框存在,如果他们有保存“名称”,他们将张贴到保存表单集合键下的操作。 –

0

你可以得到其使用以下相同名称的所有文本框的值代码:

var results = ((String[])formcollection.GetValue("mytxt").RawValue).ToList(); 
      foreach (var item in results) 
      { 
       //string name = item; 
      } 
0

当你添加一个元素动态确保你也设置它的名字。所以当你添加一个新的输入元素必须是

<input type="text" name="NewTextBox" class="form-control input-sm" placeholder="Value" name="searchvalue"> 

所以这样,无论你有多少个文本框添加,所有的都会有相同的名称。一旦你发布表单。在你的控制器中这样做。

[HTTPPOST] 
public ActionResult Search(MyModel newModel,string[] NewTextBox) 
{ 
// here as you had dynamic textbox with name = NewTextBox you 
//will get all its value binded to the above string[] 

} 

OR

可以使用retrive他们Request.form["NewTextBox"]

[HTTPPOST] 
public ActionResult Search(MyModel newModel) 
{ 
var values = Request.Form[NewTextBox];  
} 

但我会建议你,你使用MVC Model Binder采取一切后事第一种方法。你只需要有数组值来玩。

注意:请务必确保您的名称正确,并在使用MVC时使用正确的名称。因为所有的绑定都依赖于命名本身。