asp.net - 在 MVC/ASP.NET 中发布包含列表的模型

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

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

有没有办法让表格像这样

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

最佳答案

试试这个:

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

关于asp.net - 在 MVC/ASP.NET 中发布包含列表的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17468279/

相关文章:

asp.net - 我如何在中继器中的编辑模式弹出窗口中打开表单?

javascript - 当脚本是外部时 getElementByID

MVC3 中的 ASP.NET AJAX 控件?

asp.net-mvc-3 - MVC 3 EditorTemplates 不适用于生产

python - 转换元组列表,使 [(a,b,c)] 转换为 [(a,b),(a,c)]

jquery - 动态获取ID

javascript - 尝试在 Chrome 扩展程序中使用 SignalR 连接到集线器时出错

jquery - ASP.NET MVC - 页面卸载

r - 提取具有两个以上字符并匹配模式的列表元素

c - 从文本文件读取行到结构 C