在MVC / ASP.NET中发布包含List的模型

时间:2013-07-04 10:45:23

标签: asp.net asp.net-mvc-3 list post viewmodel

我知道如何post ASP.NET中表单的对象列表,但假设我想同时post其他一些值?

有没有办法获得表格,比如

<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>

发布到看起来像这样的方法?

[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 个答案:

答案 0 :(得分:5)

试试这个:

<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>