2014-02-13 55 views
1

我在我的HTML的输入框开始形式表收集问题域

@using (Html.BeginForm("Search", "Reports",FormMethod.Post, new { enctype = "multipart/form-data")) 
{ 
    <input type="text" class="form-control input-sm" placeholder="Value" name="searchvalue"> 

    <button type="button" class="btn btn-default btn-Add">+</button> 
    <input type="submit" value="Search" class="btn btn-primary" /> 
    } 

当我按下添加按钮我的形式变成了:

@using (Html.BeginForm("Search", "Reports",FormMethod.Post, new { enctype = "multipart/form-data")) 
{ 
    <input type="text" class="form-control input-sm" placeholder="Value" name="searchvalue"> 
    <input type="text" class="form-control input-sm" placeholder="Value" name="searchvalue"> 
    <button type="button" class="btn btn-default btn-Add">+</button> 
    <input type="submit" value="Search" class="btn btn-primary" /> 
    } 

我怎么能收集这个表单的值在我的控制器或有任何jQuery的方法发布到我的控制器?请帮助我。

+0

你问这个问题有多少次... 1小时前你问过同样的问题http://stackoverflow.com/questions/21746218/form-collection-issue – Nilesh

+0

我找不到答案了.. – neel

回答

0

如果添加不在模型中的额外字段,可以使用FormCollection作为模型类型,或者在HttpContext.Request.Form中查找值。

当你在两次加名searchvalue,你可能会看到它在作为的FormCollection [0] .searchvalue和[1] .searchvalue

你会需要遍历这些得到的值出他们。

1

我认为你应该使用的FormCollection获得文本框的值。如下所示:

public ActionResult Search(FormCollection collection) 
    { 
    //string searchvalue = collection.Get("SearchValue"); 
    var results = ((String[])formcollection.GetValue("SearchValue").RawValue).ToList(); 
    return View(); 
    } 
+0

为什么使用Form MVC为我们提供模型绑定功能时的集合 –

3

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

<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时使用正确的名称。因为所有的绑定都依赖于命名本身。

+1

谢谢!这正是我所需要的。 – spadelives