ASP.NET MVC3 - 动态添加一个项目数组对象 [英] ASP.NET MVC3 - Dynamically adding an item to array on object

查看:151
本文介绍了ASP.NET MVC3 - 动态添加一个项目数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个网站,用户应该能够填写一个动态的扩展形式。

I'm working on a website where the user should be able to fill out a dynamic expanding form.

我想补充一排灰色的领域,当用户给重点领域的那些之一下面的JavaScript将添加行

I would add a row with greyed out fields and when the user gives focus to one of those field the following javascript would add the line

<tr class="unSelected">
   <input name="id[]">
   <input name="blabla[]">
</tr>

$('.unSelected').focusin(function () {
  if ($(this).hasClass('unSelected')) {
    var row = $(this).clone(true);
    $(this).after(row);
    $(this).removeClass('unSelected');
  }
});

但一会怎么用剃刀和asp.net,视物不会被自动生成那么做呢?

but how would one do this using razor and asp.net, as the objects wont be autogenerated then?

推荐答案

在ASP.NET MVC,如果你有一个模型类,如:

In ASP.NET MVC, if you have a model class like:

public class PageModel
{
    public Collection<RowItem> RowItems { get; set; }
}

public class RowItem
{
    public int Id {get;set;}
    public string MoreFields { get; set; }
}

而JavaScript添加行,像这样:

And your javascript adds rows like so:

<script type="text/javascript">
    var currentRowIndex = 0;

    $(document).ready(function () {
        SetFocusEventForInputs('unSelected0');
    });

    function SetFocusEventForInputs(className) {
        var inputSelector = '.' + className;

        $(inputSelector).focusin(function () {
            AddNewRowTo(this);
            $(inputSelector).unbind('focusin').removeClass(className);
        });
    }

    function AddNewRowTo(sendingInputField) {
        currentRowIndex++;
        var className = 'unSelected' + currentRowIndex;
        var collectionNamePrefix = 'RowItems[' + currentRowIndex + '].';

        var idField = $('<input/>').attr('name', collectionNamePrefix + 'Id').attr('type', 'text').attr('class', className);
        var moreFields = $('<input/>').attr('name', collectionNamePrefix + 'MoreFields').attr('type', 'text').attr('class', className);

        var cell = $('<td></td>').append(idField).append(moreFields);
        var row = $('<tr></tr>').append(cell);

        $(sendingInputField).parents("tr").after(row);

        SetFocusEventForInputs(className);
    }
</script>
<table>
    <tr>
        <td>
            <input name="RowItems[0].Id" type="text" class="unSelected0" />
            <input name="RowItems[0].MoreFields" type="text" class="unSelected0" />
        </td>
    </tr>
</table>

在MVC默认模型联应该解决这个问题就好了,当它被发布

The default model binder in MVC should resolve it just fine when it gets posted

[HttpPost]
public ActionResult YourPostActionHere(PageModel model)
{
    var count = model.RowItems.Count();
    etc...
}

这篇关于ASP.NET MVC3 - 动态添加一个项目数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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