ASP.NET MVC 2 and lists as hidden values?

Hi,

I have a view class containing a list, this list describes the available files that the user has uploaded (displayed using the html helper).

To save this data in the view, I added the following to the view:

<%: Html.HiddenFor(model => model.ModelView.Files)%> 

I was hoping the mode.ModelView.Files list would be returned to the action on submit, but is it not?

Is it impossible to have a list as a hidden field?

Additional information: The user sends a pair of files that are saved in the service when the saved thay is referred to as a GUID, and this list is sent back to the user to display the saved images. The user makes any changes to the form and clicks submit again when the list of images is empty, when you get into the control action, why?

Best regards

+6
asp.net-mvc-2 hidden-field
source share
2 answers

Is it impossible to have a list as a hidden field?

Of course, this is not possible. The hidden field takes only one string value:

 <input type="hidden" id="foo" name="foo" value="foo bar" /> 

So, if you need a list, you need some hidden fields for each element of the list. And if these objects are complex objects, you need a hidden field for each property of each item in the list.

Or a much simpler solution for this hidden field is to present some unique identifier:

 <input type="hidden" id="filesId" name="filesId" value="123" /> 

and in the action of your controller, you must use this unique identifier to restore your collection from where you originally received it.

Another possibility is to save your model in Session (just mentioning the session to complete my answer, but this is not what I would recommend using).

+6
source share

Before starting, I would like to mention that this is an example of one of the proposed solutions, which was marked as an answer. Darrin understood this correctly, here is an example of the implementation of the proposed solution ...

I had a similar problem when I needed to store a generic list of type int in a hidden field. I tried the standard apporach, which would be the following:

 <%: Html.HiddenFor(foo => foo.ListOfIntegers) %> 

This could cause an exception. So I tried Darrin's suggestion and replaced the code above:

 <% foreach(int fooInt in Model.ListOfIntegers) { %> <%: Html.Hidden("ListOfIntegers", fooInt) %> <% } %> 

It worked like a charm for me. Thanks Darrin.

+3
source share

All Articles