简体   繁体   English

如何在ASP.NET MVC中重复表单控件并将其作为列表传递给控制器

[英]How to repeat form controls in asp.net mvc and pass them as a list to controller

I have 3 controls(one textbox, one numericbox and a date) inside a view form, these 3 forms the Model object. 我在视图表单中有3个控件(一个文本框,一个数字框和一个日期),这3个表单构成了Model对象。 There is link provided to the user, on click of this link all the 3 controls were repeated 5 times inside the form. 有一个提供给用户的链接,单击此链接后,表格中的所有3个控件都重复了5次。

I have a list of Model class as an argument type in the controller action method. 我在控制器操作方法中有一个Model类列表作为参数类型。 How to clone the form content 5 times such that it serializes properly to List? 如何克隆表格内容5次以使其正确地序列化到List?

A simpler way. 一种更简单的方法。

Model : 型号:

public class MyModel
{
    public IList<OneSetOfElements> FormSet { get; set; }
}

public class OneSetOfElements
{
    public string Name { get; set; }
    public int Age { get; set; }

    [DataType(DataType.Date)]
    public DateTime Dob { get; set; }
}

Action : 动作:

public ActionResult MyAction(MyModel model)
{
    foreach (var set in model.FormSet)
    {
        //read your data.
    }
}

View : Show the id "showMeOnUrlClick" on click 查看:点击时显示ID“ showMeOnUrlClick”

    @using (Html.BeginForm())
    {

//This would bind as first list element
        <div id="firstSet"> 
            @Html.EditorFor(m => m.FormSet[1].Name)
            @Html.EditorFor(m => m.FormSet[1].Age)
            @Html.EditorFor(m => m.FormSet[1].Dob, new { type = "date" })

        </div>

//Remaining list element
        <div id="showMeOnUrlClick" style="display: none"> 
            @for (int i = 1; i <= 6; i++)
            {
                @Html.EditorFor(m => m.FormSet[i].Name)
                @Html.EditorFor(m => m.FormSet[i].Age)
                @Html.EditorFor(m => m.FormSet[i].Dob, new {type = "date"})
            }
        </div>

        <button onclick="showTheRepeatedFields() ">Show</button>
    }

You should use jQuery to dynamically create a row with all the 3 input fields when user clicks on the Add button. 当用户单击“添加”按钮时,应使用jQuery动态创建包含所有3个输入字段的行。

So in your razor view (ex:Create), create the first row with the three form fields. 因此,在剃刀视图(例如:创建)中,使用三个表单字段创建第一行。

@using (Html.BeginForm())
{
   <a href="#" id="addRow">Add</a>
   <div id="items">
      <div class="itemRow">
         <label>Name</label> <input type="text" class="formfield" name="Name" />
         <label>Age</label>  <input type="text" class="formfield" name="Age" />
         <label>CreateDate</label><input type="text" class="formfield" name="CreateDate" />
      </div>
   </div>
    <input type="submit" id="btnSubmit" />
}

Now we will add some client side code to listen to the click event on the Add link, create a clone of the container div(with css class itemRow ) and append it to the outer container div(with id items ). 现在,我们将添加一些客户端代码来侦听“添加”链接上的click事件,创建容器div(具有css类itemRow )的克隆,并将其附加到外部容器div(具有id items )。 When user clicks the submit button, we will read the form fields and build an array of object and post that to the server using jQuery ajax. 当用户单击“提交”按钮时,我们将读取表单字段并构建对象数组,然后使用jQuery ajax将其发布到服务器。

@section Scripts
{
<script type="text/javascript">

    $(function () {

        $("#addRow").click(function (e) {
            e.preventDefault();    
            var template = $("#items").find(".itemRow").first();
            var newRow = template.clone();
            newRow.find("input.formfield").val("");
            $("#items").append(newRow);

        });

        $("#btnSubmit").click(function (e) {
            e.preventDefault();
            var _this = $(this);
            var url =_this.closest("form").attr("action");

            var rows = [];
            var items = $(".itemRow");

            $.each(items, function (i, item) {                   
                var name =  $(item).find("input[name='Name']").val();
                var age =  $(item).find("input[name='Age']").val();
                var createDt =  $(item).find("input[name='CreateDate']").val();

                var row = { Name: name, Age: age, CreateDate: createDt };
                rows.push(row);    
            });

            //Let's post to server
            $.ajax({
                type:"POST",
                url: url,
                data: JSON.stringify(rows),
                contentType: "application/json"                       
            })
            .done(function (result) {
                //do something with the result
            })                 

        });    
    });    
</script>
}

Now you need an HttpPost action method to handle your form posting. 现在,您需要一个HttpPost操作方法来处理表单发布。

[HttpPost]
public ActionResult Create(IEnumerable<CreateUser> model)
{
    foreach(var item in model)
    {
        // to do  :Save
    }
    return Json( new { status ="success"});
}

and your CreateUser view model will look like 您的CreateUser视图模型将如下所示

public class CreateUser
{
    public string Name { set;get;}
    public int Age { set; get; }
    public DateTime CreateDate { set; get; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM