开发者

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). How can I generate this editor field in my view? I assume there are MVC 3 help开发者_C百科ers I can make use of.


If you want a dropdownlist you can use the HTML.DropDownList helper method. Is this what you want or do you need to display the List as an Ordered/Unordered HTML list?

EDIT

You can create your own HTML Helper function. Assuming you use Razor you can follow the following steps

1.)Create a new .cshtml file inside App_Code directory and name it as you want (for example HTMLHelpers.cshtml)

2.)Write the following in the file

@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. For example write

@HTMLHelpers.OrderedList(Model)

2nd EDIT

You can also use Javascript to achieve that functionality. Knockout.js from Steven Sanderson is a great library that helps you to databind values to html elements.

This sample from knockout.js documentation is similar to your needs.

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.


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. 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. 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜