Yustme
Yustme

Reputation: 6255

Loop through collection with jquery

For the simplicity of the question, the model i'm sending to the view contains a property which is of type ICollection<Person> Persons { get; set; }.

In my view it's hidden like so:

@Html.HiddenFor(model => model.Persons)

Once an ActionLink is pressed, first and last name of the person will be added to a (kendo) grid.

$('#add').click(function (personObject)
    {
        var personId= $("#PersonId").val();
        alert(personId);


        return false;
    });

Some more info: The person gets selected from a dropdownlist. Behind this DDL is the ActionLink, which has a HtmlAttributepointing to the JQuery function it needs to call.

That all works fine.

What i'm trying to accomplish here, is to look up the first and last name of the person that got selected from the dropdownlist.

Based on the Id of that person, i need to get the first and last name out of the hidden "Persons" collection property:

@Html.HiddenFor(model => model.Persons)

How can I do this using JQuery?

Upvotes: 0

Views: 1037

Answers (2)

Martin Ernst
Martin Ernst

Reputation: 5679

You need to serialize your collection into a format that you can read in javascript.

For example:

@Html.Hidden("Persons", Json.Encode(Model.Persons))

Then you can parse this data using something like:

<script> 
    var persons = JSON.parse($("#Persons").val());
</script>

Upvotes: 2

Andreas
Andreas

Reputation: 250

HiddenFor won't work with collections, only single values. Why not get the names from the model or do a call to the server.

Upvotes: 0

Related Questions