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

2020-03-25 06:03发布

问题:

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="idontgiveoutmyemail@overtheinter.net" />
    <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; }
}

回答1:

Try this:

<form method="POST" action="test">
    <input type="text" name="name" value="Roryok" />
    <input type="text" name="email" value="idontgiveoutmyemail@overtheinter.net" />
    <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>