This is my situation:
I have this view model:
public class ViewModel
{
public DateTime someDate { get; set; }
public String someString { get; set; }
public List<E> someList { get; set; }
}
What I have to do is in the view set the date, write some text and then select from a list of E any number of E. The ViewModel returned in the action must have the date, the text and contain the list of selected items.
What I need to know is how to handle said list. How can I add each selected item to the models' List. I was thinking on adding a property public bool selected
to E and then send all items and filter the selected ones on the server, however I would rather not send back and forth all that data since the list can be quite large.
I am using MVC3 with razor and JQUERY AJAX for all my form posts.
If I am not making myself clear, please let me know.
Thank you.
Here's one technique that you could use to achieve this.
Let's start with the view model:
then we write some controller to handle the rendering of the view and the AJAX request:
then we move on to the
~/Views/Home/Index.cshtml
view:and finally we define an Editor template for the
E
type (~/Views/Home/EditorTemplates/E.cshtml
) which will be rendered for each element of the collection:OK, so at this stage we haven't yet written the javascript part so this should behave as a normal HTML form and when it is submitted it will send all the values to the server.
And final piece would be to AJAXify the form and POST only the records that the user selected in the request. So we could do this in a separate javascript file:
As a good article for handling dynamic lists I would recommend you the following blog post.