2

Please forgive me if this question is a duplicate, because I could not find the answer to this question anywhere else on Stack Overflow.

I have a form in ASP.NET that has multiple fields, and more fields can be added through jQuery. In my form, I want an array of friends.

This is the friend class:

public class Friend {
    public string Name { get; set; }
    public int Age { get; set; }
}

This is my form, and users can add as many friends as they want, by clicking a button that adds a row with these two fields. For example:

<table>
    <tr>
        <input type="text" name="friend[0].Name" />
        <input type="text" name="friend[0].Age" />
    </tr>
    <tr>
        <input type="text" name="friend[1].Name" />
        <input type="text" name="friend[1].Age" />
    </tr>
    <tr>
        <input type="text" name="friend[2].Name" />
        <input type="text" name="friend[2].Age" />
    </tr>
    ...
</table>

How would I access these as a list of friends, in my function in the controller?

1 Answer 1

3

I Think you're almost there,

<form method="post" action="/Home/UpdateFriends">

    <input type="text" name="[0].Name" value="Curious George" />
    <input type="text" name="[0].Age" value="20" />

    <input type="text" name="[1].Name" value="Code Complete" />
    <input type="text" name="[1].Age" value="50" />



    <input type="submit" />
</form>

controller should look like this

//Action method on HomeController
public ActionResult UpdateFriends(ICollection<Friend> friends) {
    //your code here
}

this article explains it more in depth.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.