如何将通用列表项发送到控制器

时间:2013-05-25 15:17:34

标签: asp.net-mvc asp.net-mvc-4 controller

我有一个类似的模型:

public class Invoice
{
int Code{get;set;}
List<InvoiceItem> InvoiceItems{get;set;}
}

我在表中填写InvoiceItems,我希望在控制器中将表项作为InvoiceItems

  [HttpPost]
        public virtual ActionResult Create(Invoice model)
        {
           //Save Invoice
            return View();
        }

如何填写InvoiceItems并将其发送给控制器?

enter image description here

2 个答案:

答案 0 :(得分:1)

你的HTML的结果应该是这样的     

    <input type="text" name="Code" value=""/>
    ...
    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td><input type="hidden" name="InvoiceItems[0].Name" value="InvoiceItem1"/></td>
            </tr>
            <tr>
                <td>2</td>
                <td><input type="hidden" name="InvoiceItems[1].Name" value="InvoiceItem2"/></td>
            </tr>
            <tr>
                <td>3</td>
                <td><input type="hidden" name="InvoiceItems[2].Name" value="InvoiceItem3"/></td>
            </tr>
        </tbody>
    </table>
    <button type="submit">Submit</button>
</form>

这样您就可以使用普通表单提交或ajax

// assuming you have only one form. otherwise use more specific selector
var $form = $("form");
var data = $form.serializeArray();
var url = $form.attr("href") || document.URL;
$.post(url, data, yourCallbackFunction);

其余的由ModelBinder完成。关键部分是维护InvoiceItems索引。它们必须从0开始并且是顺序的。即0,1,2,3等。如果你跳过某个索引,modelbinder将结束你的索引被破坏的列表。

答案 1 :(得分:0)

列表可以用准二维数组表示:

$arr = 
    array(
        array(
            {
                "key":"value",
                "key2":"value2"
            },
            {
                "key":"value",
                "key2":"value2"
            }
        ),
        array(
            {
                "key":"value",
                "key2":"value2"
            },
            {
                "key":"value",
                "key2":"value2"
            }
        )
    );

(json_encode)

可以阅读,例如$ val = $ arr [“0”] [“0”] [“key2”];

这只是一个例子&gt;使用并组合Array-,Object-和Json-Syntax以使您的列表符合您的需求。使用json非常方便,具有非常“源”和面向对象的编码以及简单的数据处理。

ps:对我来说,你的问题似乎很不清楚,不知道你究竟是针对什么......