开发者

Posting back custom collections in ASP.NET MVC2

开发者 https://www.devze.com 2023-01-31 09:30 出处:网络
I have an generic enumerable of type BookCover that I wan\'t to display to the user. They can only choose one book cover from the selection available.

I have an generic enumerable of type BookCover that I wan't to display to the user. They can only choose one book cover from the selection available.

 public class BookCover {
        public bool IsSelected { get; set; }
        public string CoverPathThumb 开发者_运维百科{ get; set; }
        public string SpinePathThumb { get; set; }
        public string BackPathThumb { get; set; }
    }

My action method is similar to

public ActionResult SelectCover(IEnumerable<BookCover> covers);

In my template I just enumerate and write out the desired HTML but the problem is I don't know how to get the data from the post back.

How do I name my <input> id's? Is there another reason IEnumerabme isn't populating when the post back occurs?


@Vince: You can customize the ModelBinder. And in the ModelBinder, you can get data from HttpContext.Request.Form, after that you will build your new BookCover collection. Finallly you call

public ActionResult SelectCover(IEnumerable<BookCover> covers);

And remember registering it in Global.asax as:

ModelBinders.Binders[typeof(IEnumerable<BookCover>)] = new YourModelBinderName();

You can get references at here and here is discussion about it. Hope this help you!


You should add an ID you BookCover type, and then use this ID to identify the cover that the user selected. If you retrieve your covers from a database, just use this ID in your class.


I think you can do something like this:

<% foreach(var item in covers) { %>
     <%: Html.EditorFor(x => item.IsSelected) %>
<% } %>


The name of your inputs should be in the form:

covers[0].IsSelected
covers[0].CoverPathThumb
covers[0].SpinePathThumb 
covers[0].BackPathThumb 

E.g.

<input type="text" name="covers[0].CoverPathThumb" />

Increase 0 for each cover entry.

0

精彩评论

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