roryok
roryok

Reputation: 9645

POSTing a Model containing a List in MVC / ASP.NET

I know how to post a list of objects to a form in ASP.NET, but suppose I want to post some other values at the same time?

Is there a way to have a form, like this

<form method="POST" action="test">
    <input type="text" name="name" value="Roryok" />
    <input type="text" name="email" value="[email protected]" />
    <input type="text" name="[0].hobby" value="dibbling" />
    <input type="text" name="[0].level" value="amateur" />
    <input type="text" name="[0].hobby" value="fargling" />
    <input type="text" name="[0].level" value="intermediate" />
    <input type="text" name="[2].hobby" value="garbling" />
    <input type="text" name="[2].level" value="expert" />
</form>

Post to a method that looks something like this?

[HttpPost]
public ActionResult test(MyViewModel model){
    /// do some stuff with the model here 
    return View();
}

public class MyViewModel{
    public string name { get; set; }
    public string email { get; set; }
    public List<Hobby> hobbies { get; set; }
}

public class Hobby{
    public string hobby { get; set; }
    public string level { get; set; }
}

Upvotes: 3

Views: 4229

Answers (1)

karaxuna
karaxuna

Reputation: 26930

Try this:

<form method="POST" action="test">
    <input type="text" name="name" value="Roryok" />
    <input type="text" name="email" value="[email protected]" />
    <input type="text" name="hobbies[0].hobby" value="dibbling" />
    <input type="text" name="hobbies[0].level" value="amateur" />
    <input type="text" name="hobbies[1].hobby" value="fargling" />
    <input type="text" name="hobbies[1].level" value="intermediate" />
    <input type="text" name="hobbies[2].hobby" value="garbling" />
    <input type="text" name="hobbies[2].level" value="expert" />
</form>

Upvotes: 5

Related Questions