我有一个网页来提交食谱。有5个成分领域。如果配方需要超过5种成分,则有一个“添加其他成分”的按钮,一些java脚本会加载另一种配料输入供他们使用。
我不知道如何正确地将这些数据发布到MVC4/C#的后端。HTML表单 - 如何处理动态输入数量?
我可以给他们所有相同的id =成分,并收集他们作为字符串ingrdient []?或者当输入数量可以改变时获得表格输入的最佳做法是什么?
谢谢。
我有一个网页来提交食谱。有5个成分领域。如果配方需要超过5种成分,则有一个“添加其他成分”的按钮,一些java脚本会加载另一种配料输入供他们使用。
我不知道如何正确地将这些数据发布到MVC4/C#的后端。HTML表单 - 如何处理动态输入数量?
我可以给他们所有相同的id =成分,并收集他们作为字符串ingrdient []?或者当输入数量可以改变时获得表格输入的最佳做法是什么?
谢谢。
确定这里是一个示例: 您可以使用此方法:
<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; }
}
}
如果您将同名方括号括起来,您应该能够在提交表单时将它们作为数组联系到它们。
<input type="text" name="data[]" value="">
我不知道到底什么是最好的办法就MVC4而言,但你绝对可以给所有的输入同名并提交后,你应该能够找回它们在服务器上通过只看HttpContext.Request.Params
对象。
在阵列张贴这将是最简单的解决方案。您可以在控制器中使用列表或列表来一次获取所有数据,而不是遍历FormController或HttpContext.Request.Params。 –
Rajesh
2012-08-09 05:35:28
@Rajesh我如何将它们全部作为数组发布?感谢您的帮助。 – Kyle 2012-08-09 05:37:04