【问题标题】:HTML form - how to handle dynamic number of inputs?HTML 表单 - 如何处理输入的动态数量?
【发布时间】:2012-08-09 01:15:28
【问题描述】:

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

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

谢谢。

【问题讨论】:

  • 将它发布到数组中将是最简单的解决方案。您可以在控制器中使用 List 或 List 一次获取所有数据,而不是通过 FormController 或 HttpContext.Request.Params 进行迭代。
  • @Rajesh 我如何将它们全部发布为数组?谢谢你的帮助。

标签: c# html asp.net-mvc


【解决方案1】:

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

 <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; }
    }
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 2022-06-15
        • 1970-01-01
        • 2012-11-21
        相关资源
        最近更新 更多