带有 EditorFor 模板的自定义 HtmlHelper
我有一个 EF 模型,我将其传递到视图中以进行创建和编辑。我有一个字符串字段 (varchar(100)),用于存储潜在值的分隔列表。该列表应该由复选框列表填充。我知道如何显示我的硬编码列表,但我试图弄清楚如何处理 EditorFor 模板,以便我可以将选中的值转换为分隔字符串。
例如,我的 HtmlHelper 中可能有一系列包含水果的复选框(即:苹果、香蕉、樱桃、草莓)。如果选择其中两个,我希望将这些值(即:Apple,Strawberry)传递给控制器上的方法以保存在数据库中。
任何想法我如何能够实现这一目标。
I have an EF model that I'm passing into the views to Create and Edit. I have a field that is a string (varchar(100)) that is meant to store a delimited list of potential values. That list should be populated by a checkboxlist. I know how to get my hardcoded list to display, but I'm trying to figure out how to handle the EditorFor template so that I can convert the checked values to a delimited string.
For example, I may have a series of checkboxes in my HtmlHelper that contain fruit (ie: Apple, Banana, Cherry, Strawberry). If two of them are chosen, I want those values (ie: Apple,Strawberry) to be passed to the method on the controller to be saved in the database.
Any ideas how I may be able to accomplish this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我有两种可能的方法来做到这一点。可以以将值作为数组发送到服务器的方式命名复选框,然后在其中构建分隔字符串。这显然不是首选,因为您可能必须在许多地方使用此逻辑。
另一种方法是在模板中使用一些 javascript,在单击复选框时构建分隔字符串并将其放入隐藏字段中,该字段将提交给您的操作方法。
http://jsfiddle.net/infernalbadger/Xjjf2/1/
There are two possible ways I would do this. Either name your checkboxes in a way that the values will be sent to the server as an array and then build the delimited string there. This obviously wouldn't be preferred as you might then have to use this logic in many places.
The other way is to have some javascript in the template that builds your delimited string as checkboxes are clicked and puts it into a hidden field which is what get's submitted to your action method.
http://jsfiddle.net/infernalbadger/Xjjf2/1/