简体   繁体   English

在ASP.NET MVC 3视图中,如何为列表字段生成编辑器?

[英]In an ASP.NET MVC 3 view, how can I generate an editor for a list field?

I am creating a form in an ASP.NET MVC 3 view, in which one field is to specify a list of ints (corresponding to List<int> in the edited model). 我在ASP.NET MVC 3视图中创建一个表单,其中一个字段用于指定一个int列表(对应于已编辑模型中的List<int> )。 How can I generate this editor field in my view? 如何在我的视图中生成此编辑器字段? I assume there are MVC 3 helpers I can make use of. 我认为我可以使用MVC 3帮助程序。

If you want a dropdownlist you can use the HTML.DropDownList helper method. 如果需要下拉列表,则可以使用HTML.DropDownList帮助器方法。 Is this what you want or do you need to display the List as an Ordered/Unordered HTML list? 这是您想要的还是需要将列表显示为有序/无序HTML列表?

EDIT 编辑

You can create your own HTML Helper function. 您可以创建自己的HTML Helper函数。 Assuming you use Razor you can follow the following steps 假设您使用Razor,则可以按照以下步骤操作

1.)Create a new .cshtml file inside App_Code directory and name it as you want (for example HTMLHelpers.cshtml) 1.)在App_Code目录中创建一个新的.cshtml文件,并根据需要命名(例如HTMLHelpers.cshtml)

2.)Write the following in the file 2)在文件中写入以下内容

@helper OrderedList(List<int> list) {
    <ul>
        @foreach (var item in list)
        {
            <li>@item</li>
        }
    </ul>
}

3.)Now in your view you can call your new function. 3)现在,您可以在视图中调用新功能。 For example write 例如写

@HTMLHelpers.OrderedList(Model)

2nd EDIT 第二次编辑

You can also use Javascript to achieve that functionality. 您也可以使用Javascript实现该功能。 Knockout.js from Steven Sanderson is a great library that helps you to databind values to html elements. Steven Sanderson的Knockout.js是一个很棒的库,可以帮助您将值数据绑定到html元素。

This sample from knockout.js documentation is similar to your needs. kickout.js文档中的此示例与您的需求类似。

You can also view this blog post from Steven Sanderson that explains how to use Knockout.js with a variable length list and how to submit the list data back to server. 您也可以查看Steven Sanderson的博客文章 ,其中介绍了如何将Knockout.js与可变长度列表一起使用以及如何将列表数据提交回服务器。

Phil Haack's blog post discusses every aspect of using model binding to a list: controller code, view code, complex and primitive types, dictionary binding. Phil Haack的博客文章讨论了使用模型绑定到列表的各个方面:控制器代码,视图代码,复杂和原始类型,字典绑定。 From the first paragraph of that blog post, MVC builtin model binder binds List with just passing number of same named query string (or form when posting) parameters to controller. 从该博客文章的第一段开始,MVC内置模型联编程序将List与仅传递相同名称的查询字符串(或发布时的表单)参数的编号绑定到控制器。 Example

<form method="get">
   <input type="checkbox" name="ints" value="1" />
   <input type="checkbox" name="ints" value="4" />
   <input type="checkbox" name="ints" value="2" />
   <input type="checkbox" name="ints" value="8" />
   <input type="submit" />
</form>

This would bind correctly to 这将正确绑定到

public ActionResult UpdateInts(List<int> ints) {

  return View(ints);
}

See that blog post for the complete information 有关完整信息,请参阅该博客文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM