在ASp.NET MVC表单中访问由jQuery动态创建的文本框中的值

时间:2013-02-22 04:08:57

标签: jquery asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我想在我的MVC添加/编辑表单中动态添加文本框。

我有一个名为“Interests”的字段,用户应该可以通过点击“Add another”文本框添加他/她喜欢的任意数量的兴趣。

这个,我可以使用JQuery。

我想生成一个字符串,该字符串将包含上述字段“Interests”中的逗号分隔值。

假设用户添加了三个文本框,其值为网球,足球和棒球。我想将这些值组合在逗号分隔的字符串中,并将它们传递给Model.Interest,这是我的用户模型中的一个字段。

有没有简单的方法来做到这一点..

2 个答案:

答案 0 :(得分:3)

比这简单得多,只需在输入中添加name =''约定,mvc的binder就会得到值。

你实际上有两个选择这样做...... 1. name =“textbox [0] .Name”等。 2.创建自己的Binder, 并根据需要绑定您的输入。 你不必重新发明任何东西。

请原谅我花了这么长时间来编辑我的答案,这是一个例子: 模特:

public class Person
{
    public Person()
    {
        InterestList = new List<Interest>();
    }

    public IList<Interest> InterestList { get; set; }
}

public class Interest
{
    public string Name { get; set; }
}

The Binder:

public class InterestListBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, 
        ModelBindingContext bindingContext)
    {
        var person = new Person();
        foreach (var i in controllerContext.RequestContext.HttpContext.Request.Form.AllKeys)
        {
            person.InterestList.Add(new Interest
                {
                    Name = controllerContext.RequestContext.HttpContext.Request.Form[i]
                });
        }
        return person;
    }
}

附加活页夹的Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        ModelBinders.Binders.Add(typeof(Person), new InterestListBinder());
    }
}

控制器:

   public class HomeController : Controller
   {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Person person)
        {
            return View("Index", person);
        }
    }

现在看来:

@model Data.Services.DataBinders.Person



<div>
    <form action="@Url.Action("Index", "Home")" method="POST">
        @{
            if (Model != null && Model.InterestList.Any())
            {
                foreach (var tb in Model.InterestList)
                {
                    <input type="text" value="@tb.Name"/>
                }
            }
        }
        <input type="button" value="add" id="add" />
        <input type="button" value="remove" id="remove" />
        <input type="submit" value="Submit" />
    </form>
</div>

生成动态输入的javascript,您可以添加任何您喜欢的名称:

    <script>
    (function ($) {
        var demo = {
            init: function () {
                this.elements = null;
                this.cache();
                this.bindEvents();
                return this;
            },
            cache: function () {
                this.elements = new Array();
            },
            bindEvents: function () {
                $("#add").on("click", this.add);
                $("#remove").on("click", this.remove);
            },
            add: function () {
                var self = demo;
                var $elem = $("<input type='text' \>");
                self.elements.push($elem);
                self.render();
            },
            remove: function () {
                var self = demo;
                $.each(self.elements, function (index, elem) {
                    elem.remove();
                });
                self.elements.splice(0, 1);
                self.render();
            },
            render: function () {
                var self = demo;
                for (var e in self.elements) {
                    self.elements[e].attr("name", "Interest" + e);
                    $("form").append(self.elements[e]);
                }
                console.log(self.elements);
            }
        };
        window.load = demo.init();
    })(jQuery)
</script>

答案 1 :(得分:2)

如果您的所有文本框共享一个类txtInterestsToGrab,您可以将它们全部合并为逗号分隔的字符串,并将它们发布到名为saveInterests的假设操作方法

    var data = $('.txtInterestsToGrab').val().join(',');



    $.ajax({
        type: "POST",
        url: "/Stuff/saveInterests/",
        dataType: 'json',
        traditional: true,
        data: data,
        success: function () {
        }
    });

如果您决定不使用以逗号分隔的字符串,而是使用列表(我高度高度推荐)

    var data = $('.txtInterestsToGrab').val();