2012-08-09 56 views
0

我有一個網頁來提交食譜。有5個成分領域。如果配方需要超過5種成分,則有一個「添加其他成分」的按鈕,一些java腳本會加載另一種配料輸入供他們使用。
我不知道如何正確地將這些數據發佈到MVC4/C#的後端。HTML表單 - 如何處理動態輸入數量?

我可以給他們所有相同的id =成分,並收集他們作爲字符串ingrdient []?或者當輸入數量可以改變時獲得表格輸入的最佳做法是什麼?

謝謝。

+0

在陣列張貼這將是最簡單的解決方案。您可以在控制器中使用列表或列表來一次獲取所有數據,而不是遍歷FormController或HttpContext.Request.Params。 – Rajesh 2012-08-09 05:35:28

+0

@Rajesh我如何將它們全部作爲數組發佈?感謝您的幫助。 – Kyle 2012-08-09 05:37:04

回答

2

確定這裏是一個示例: 您可以使用此方法:

<div class="editor-field"> 
     <input type="text" name="MyModelArray[0].Sugar" value="" /> 
     <input type="text" name="MyModelArray[1].Tea" value="" /> 
     <input type="text" name="MyModelArray[0].Sugar" value="" /> 
     <input type="text" name="MyModelArray[1].Tea" value=""/> 
    </div> 
    <p> 
     <input type="submit" value="Create" /> 
    </p> 

現在,您可以使用您的控制器得到這樣的:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
namespace MvcApplication1.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public ActionResult Index(List<Ingredient> MyModelArray) //Put a breakpoint here to see 
     { 
      return View(); 
     } 
     [HttpPost] 
     public ActionResult About(List<string> MyStringArray) //Use this if you don't want a model 
     { 
      return View(); 
     } 
    } 
    public class Ingredient 
    { 
     public string Sugar { get; set; } 
     public string Tea { get; set; } 
    } 
} 
3

如果您將同名方括號括起來,您應該能夠在提交表單時將它們作爲數組聯繫到它們。

<input type="text" name="data[]" value=""> 
0

我不知道到底什麼是最好的辦法就MVC4而言,但你絕對可以給所有的輸入同名並提交後,你應該能夠找回它們在服務器上通過只看HttpContext.Request.Params對象。