0

My ViewModel contains a collection of some object (IEnumerable). The items of the collection are displayed on rows into a tag. When I submit my form, it's triggering submit jQuery function to validate itself. I need to get the values from that displayed table and transforms into a object.

Check this out:

//
// the table to display my collection content
<div id="publications">
    Items to publish:

    <table>
        <thead><tr>
            <td></td>
            <td>Item</td>
        </tr></thead>

        <tbody>
            @{
                for (int counter = 0; counter < Model.Publications.Count; ++counter)
                {
                    <tr>
                        <td>
                            @Html.HiddenFor(m => Model.Publications[counter].ID)
                            @Html.CheckBoxFor(m => Model.Publications[counter].Selected)
                        </td>
                        <td>
                            @Html.HiddenFor(m => Model.Publications[counter].ItemID)
                            @Html.DisplayTextFor(m => Model.Publications[counter].ItemDescription)
                        </td>
                    </tr>
                }
            }
        </tbody>
    </table>
</div>

//
// The Publication ViewModel
public class PublicationViewModel {
    public string ID { get; set; }
    public bool Selected { get; set; }
    public string ItemID { get; set; }
    public string ItemDescription { get; set; }
}

//
// The main ViewModel
public class MainViewModel {
    public string ID { get; set; }
    public string Name { get; set; }
    public IEnumerable<PublicationViewModel> Publications { get; set; }
}

The doubt is how to translate that table into a serialized object with jQuery. Thank you so much, guys!

Kiwanax
  • 1,265
  • 1
  • 22
  • 41

1 Answers1

1

Put your code inside a <form> and use Jquery serialize.

<form id="publications">
    Items to publish:

    <table>
        <thead><tr>
            <td></td>
            <td>Item</td>
        </tr></thead>
            <tbody>
            @for (int counter = 0; counter < Model.Publications.Count; ++counter)
            {
                <tr>
                    <td>
                        @Html.HiddenFor(m => Model.Publications[counter].ID)
                        @Html.CheckBoxFor(m => Model.Publications[counter].Selected)
                    </td>
                    <td>
                        @Html.HiddenFor(m => Model.Publications[counter].ItemID)
                        @Html.DisplayTextFor(m => Model.Publications[counter].ItemDescription)
                    </td>
                </tr>
            }
        </tbody>
    </table>
</form>

and your jQuery script:

$('form').submit(function() {
    alert($(this).serialize());
    return false;
});
lante
  • 7,192
  • 4
  • 37
  • 57