ASP.NET动态MVC4表单生成 [英] ASP.NET MVC4 dynamic form generation

查看:90
本文介绍了ASP.NET动态MVC4表单生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的ASP.NET MVC,需要一些帮助。我有必要建立其中动态创建的表格的形式。例如,让我们说我有一个名为Person模型。人有一个名字和姓氏。形式我想允许用户输入的人的姓和名。我知道该怎么做,但我不知道怎么做是允许用户添加多个人员,使一个单一的表单提交。

I am new to ASP.NET MVC and need some help. I have a need to create a form where the form is dynamically created. For example let's say I have a model named Person. The Person has a first and last name. In the form I want to allow the user to enter the first and last name of the person. I know how to do that, but what I don't know how to do is allow the user to add multiple persons and make that a single form submission.

在页面(视图)的初始加载它会默认显示两个空文本框(对于姓和名)。我也有一个附加按钮,允许用户将另一行添加到窗体,并表现出同样的2文本框的第二人。现在,如果用户提交它,它就会有2个文本框的名字和2个姓。

On the initial load of the page (view) it would by default show two empty textboxes (for first name and last name). I would also have an add button that would allow the user to add another row to the form and show the same 2 textboxes for the 2nd person. Now if the user submits it, it would have 2 textboxes for the first name and 2 for the last name.

我不知道是否有一种方法可以做到这一点没有回发。或回发我唯一的选择?

I don't know if there is a way to do this without post backs. Or is posting back my only option?

编辑:忘了提我使用的剃刀引擎

Forgot to mention I am using the Razor engine.

感谢

推荐答案

有不需要多个职位。你希望你的表格发送人的阵列到你的动作。该行动将是这样

There is no need for multiple POSTs. You want your form to send an array of Person to your action. The action will be something like

[HttpPost]
public ActionResult AddPeople(Person[] people){ ... }

要实现这一目标,必须枚举视图输入字段。他们必须进行索引,以0开始,并相应地递增,如:

To achieve that, you must enumerate the input fields on your view. They must be indexed, starting in 0 and incrementing accordingly, like:

@using(Html.BeginForm("AddPeople","TheController", FormMethod.Post))
{
  <input type="text" name="people[0].FirstName" />
  <input type="text" name="people[0].LastName" />
  ...
  <input type="text" name="people[1].FirstName" />
  <input type="text" name="people[1].LastName" />
  ...
  <input type="text" name="people[n].FirstName" />
  <input type="text" name="people[n].LastName" />
}

您必须添加使用JavaScript的新领域,用一个简单的DOM操作。只要记得把索引秩序。

You must add the new fields using javascript, with a simple DOM manipulation. Just remember to keep the indexes in order.

这篇关于ASP.NET动态MVC4表单生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆