如何动态地创建/删除元素,并允许模型绑定在踢? [英] How to dynamically create/remove elements and allow model binding to kick in?

查看:145
本文介绍了如何动态地创建/删除元素,并允许模型绑定在踢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做到了这一点,在过去,我可能不得不做一遍,但我之前,我希望把它扔出去那里看看人们如何处理它。

I've done this in the past, and i may have to do it again, but before i do, i want to throw it out there to see how people handle it.

的Razor视图:

<ul>
   @Html.EditorFor(model => model.Questions)
</ul>

这可能会产生:

<ul>
   <li><input type="text" id="Questions_0__Title" name="Questions[0].Title" value="hi"/></li>
   <li><input type="text" id="Questions_1__Title" name="Questions[1].Title" value="hi2"/></li>
<ul>

pretty死的简单。

Pretty dead simple.

现在,我需要让用户的添加,编辑或删除任何这些问题。

Now, i need to allow the user to add, edit or remove any of those "Questions".

有关编辑,很容易 - 没有工作职位月薪。但是对于添加/删除,如果我是用jQuery做到这一点,我将需要聪明我产生了id和名属性的方式(如获得有多少计数,加1等),并删除我愿意重新渲染的一些元素(例如,如果一个被删除了,我需要改变id和名属性为-1以下所有元素)。

For Edit, it's easy - no work req'd. But for add/delete, if i were to do it with jQuery, i would need to be smart about the way i generate the "id" and "name" attributes (e.g get a count of how many is there, add 1, etc), and for delete i would to "re-render" some elements (for example, if one was deleted, i would need to change the "id" and "name" attributes to be -1 for all following elements).

这一切是因为它是一个形式,它必须是模型的约束。

All of this is because it's a form, and it needs to be model bound.

这对我来说是太毛茸茸的,所以过去后,我做了一个AJAX调用与任何的形式在服务器上,然后添加/删除控制器中的元素,呈现局部视图。这样,所有的元素都准备将模型绑定。我还需要一点点,但jQuery的,但远不一样多。

That to me is too hairy, so in the past, i have done an AJAX call to the server with whatever is on the form, then add/remove elements in the controller, and render a partial view. This way all the elements are "ready to be model bound". I still need a little but of jQuery, but nowhere near as much.

有没有人找到一个更好的办法?

Has anyone found a better way?

推荐答案

所以,我想到了一个更好的解决方案,这需要没有太大的JS的。

So i thought of a better solution, that requires not much JS at all.


  1. 在我的控制器,我创建了有100元的典范。所有空,但newed了起来,并用CSS类的隐藏

  2. 基于现有的值多少填写,我更新的元素,包括删除隐藏的CSS类。

  3. 然后我用CSS来隐藏那些与隐藏的CSS类。

  4. 当我点击添加更多,我从第3个元素去掉隐藏类。

  5. 当我点击删除,我只需将隐藏类回。

简单,为什么没有我之前想到这一点。

Easy, why didn't i think of this before.

这篇关于如何动态地创建/删除元素,并允许模型绑定在踢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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