ASP.NET MVC3 - 动态添加项目到对象上的数组
我正在一个网站上,用户应该能够填写一个动态扩展窗体。ASP.NET MVC3 - 动态添加项目到对象上的数组
我想补充一排灰色的领域,当用户给出聚焦到这些领域之一下面的JavaScript将增加线路
<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 ,因为物体不会自动生成呢?
在ASP.NET MVC,如果你有一个模型类,如:
public class PageModel
{
public Collection<RowItem> RowItems { get; set; }
}
public class RowItem
{
public int Id {get;set;}
public string MoreFields { get; set; }
}
而JavaScript添加行,像这样:
<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的默认模式粘结剂应解决它就好了,当它张贴
[HttpPost]
public ActionResult YourPostActionHere(PageModel model)
{
var count = model.RowItems.Count();
etc...
}
你可以这样做,因为在上面的代码示例中,你正在使用jQuery,当然也支持ASP.NET MVC。
也许我不明白你,但我没有看到上面的代码示例中的任何PHP代码。
我可能会一直不好解释 在php中,我会做类似 $ objWithArray = new objWithArray(); $ i = 0; ($ set [($ _ POST [“id”] [$ i])){ $ obj = new obj($ _ POST [“id”] [$ i]); $ objWithArray-> addObj($ obj); $ i ++; } 但在asp.net可以做 [HttpPost] 公众的ActionResult方法(ObjWithArray德){} 这要是字段命名为正确会自动添加它们。 你现在明白吗? :/ – 2011-06-01 10:43:02
你想要做的是不依赖于PHP或Asp.Net的客户端脚本,因此无论你的代码是由什么编写的。这也应该在Asp.Net mvc中工作。
如果您想要收集新的控制数据以在服务器端使用它,您可以通过JavaScript收集它并将其分配到可以在服务器端访问的隐藏字段中。您可以通过将值保存在一个字符串中并使用任何分隔符分隔来使用一个隐藏字段。
是的,但然后我将不得不通过手动访问字段生成对象服务器端,我的想法是要避免 – 2011-06-01 09:48:21
你可能只是缺少脚本标签?像其他人说的那样,javascript是平台独立的。
<tr class="unSelected">
<input name="id[]">
<input name="blabla[]">
</tr>
<script src="/Scripts/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$('.unSelected').focusin(function() {
if ($(this).hasClass('unSelected')) {
var row = $(this).clone(true);
$(this).after(row);
$(this).removeClass('unSelected');
}
});
});
</script>
谢谢,这真是太棒了! – 2011-06-03 09:58:13