0

我有一个提交食谱的网页。成分有 5 个字段。如果配方需要超过 5 种成分,则有一个“添加另一种成分”按钮,并且一些 java 脚本会加载另一种成分输入供他们使用。
我不确定如何将这些数据正确地发布到我的后端,即 MVC4/C#。

我可以给他们所有相同的 id=ingredient 并将它们作为字符串 ingrdient[] 收集吗?或者当输入的数量可以改变时,获取表单输入的最佳实践是什么?

谢谢。

4

3 回答 3

3

如果您使用方括号给出相同的名称,您应该能够在提交表单时将它们作为数组访问。

<input type="text" name="data[]" value="">
于 2012-08-09T01:19:55.563 回答
3

好的,这是一个示例:您可以使用这种方法:

 <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; }
    }
}
于 2012-08-09T06:07:41.583 回答
0

就 MVC4 而言,我不确切知道什么是最好的方法,但是您绝对可以为所有输入提供相同的名称,并且在提交后,您应该能够通过查看HttpContext.Request.Params对象在服务器端检索它们。

于 2012-08-09T01:20:09.377 回答