在MVC中将模型绑定到列表

3

我无法在服务器端检索简单的列表。请问有人能指导我正确的方向吗?

public class TestList
{
    public string id { get; set; }
    public string name { get; set; }
    public string location { get; set; }
}

表单:

@model List<SampleMVC4App.Controllers.TestList>
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>
@using (Html.BeginForm())
{           
    <input name="cust" value="1" type="hidden" />
    <input name="[1].id" value="de107502-284d-459b-80a1-762ce0860cd8" type="hidden" />    
    <input name="[1].name" value="test1" type="hidden" />    
    <input name="[1].location" value="location1" type="hidden" />    
    <a id="AddAnother" href="#">Add</a>
    <input type="submit" value="submit" />
}

控制器:

[HttpPost]
public ActionResult Edit(ICollection<TestList> cust) **<---Null**
{
   return View();
}

您的输入字段名称看起来非常奇怪。我担心它们是不正确的。 - Cam
你能展示一下你是如何生成表单的吗?包括渲染视图的操作和视图本身? - Brad Christie
戴,我正在尝试使用具有唯一ID的隐藏变量。通过使用索引,我能够检索它。 - Sunny
Sundeep,你知道RAZOR有@html.hiddenfor()吗? - Dave Alperovich
是的。我只是尝试使用静态值来了解它的工作原理。虽然页面上只有一个项目,但它在httppost中可用作cust [0]。 - Sunny
显示剩余3条评论
3个回答

2

经过几个小时的工作,我通过以下更改成功解决了问题

<input name="cust" value="1" type="hidden" />

为了

<input name="Index" value="1" type="hidden" />

1
以下是有关模型绑定到列表的更多信息,来自Hanselman:http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx - Dan Esparza

1

请尝试这个。 您的模型是正确的。 在cshtml页面尝试这个

 @model List<SampleMVC4App.Controllers.TestList>
    @{
        ViewBag.Title = "Index";
    }
    <h2>
        Index</h2>
    @using (Html.BeginForm())
    {           
        foreach(SampleMVC4App.Controllers.TestList tl in Model)
{
     @model.hiddenfieldfor () // Like this your list will be rendered.
}
    }

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接