动态地添加项目到视图和张贴回控制器(ASP.NET MVC 4) [英] Dynamically adding items into view and posting back to controller (ASP.NET MVC 4)

查看:74
本文介绍了动态地添加项目到视图和张贴回控制器(ASP.NET MVC 4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC 4应用程序与模型,包含和保藏中心(的IEnumerable< T> 的IList< T> ),例如:

I have a ASP.NET MVC 4 app with model, that contains and colection (IEnumerable<T> or IList<T>), i.e.:

class MyModel
{
  public int Foo { get; set; }
  public IList<Item> Bar { get; set; }
}

class Item
{
  public string Baz { get; set; }
}

和我呈现数据,鉴于经典 @for ... @ Html.EditorFor ... 广告等。现在有必要添加的在客户端导入动态新项目,然后将它张贴回服务器。

And I render the data in view with classic @for..., @Html.EditorFor... ad so on. Now there's a need to add on client side to add dynamically new items and then post it back to server.

我正在寻找一个简单的解决方案来处理增加(在JavaScript),又名不会手动创建所有的投入等,大概从编辑模板视图得到它弄好了。并增加它的方式,当表单提交回服务器模型绑定就能够正确地创建的IList&LT; T&GT; 收集,又名投入一些聪明的处理的名字。我读了一堆的文章,但没有什么是容易的,可靠的工作(没有魔法串像集合变量名,AJAX回调到服务器,...)。

I'm looking for an easy solution to handle the adding (in JavaScript), aka not manually creating all the inputs etc. Probably to get it somehow from editor template view. And to add it the way that when the form is submitted back to server the model binder will be able to properly create the IList<T> collection, aka some smart handling of inputs' names. I read a bunch of articles, but nothing that was easy and worked reliably (without magic strings like collection variable names, AJAX callbacks to server, ...).

到目前为止这个看起来很有希望,但我想,而依靠在服务器上渲染(事先已知的项目)。

So far this looks promising, but I'd like to rather rely on rendering (items known in advance) on server.

推荐答案

最后我做了类似的东西href=\"http://stackoverflow.com/a/12205084/370671\"> STO是在暗示什么,但使用自定义(非线性)指数集合的由菲尔哈克建议。

At the end I did similar stuff what STO was suggesting, but with the custom (non-linear) indices for collections suggested by Phil Haack.

此元素使用手动命名(所以我不直接绑定到该模型),我可以使用自定义实例(空元素模板)。我也创造了一些辅助方法来生成我code的实例,因此它更容易产生code从模型或空的实际情况。

This uses manual naming of elements (so I'm not binding directly to the model) and I can use custom instances (for empty element templates). I've also created some helper methods to generate me the code for the instance, so it's easier to generate code for actual instances from the model or empty ones.

这篇关于动态地添加项目到视图和张贴回控制器(ASP.NET MVC 4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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