【问题标题】:Binding to a List property of a Model绑定到模型的列表属性
【发布时间】:2013-07-09 00:35:02
【问题描述】:

我有以下型号

public class FooContainer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IList<Foo> Foos { get; set; }
}

public class Foo
{
    public string Name {get; set; }
    public string Description {get; set;}
}

示例控制器

public class FooController : Controller
{
    public ActionResult Index(){
        return View(new FooContainer());
    }

    [HttpPost]
    public ActionResult Index(FooContainer model){
        //Do stuff with the model
    }
}

我想创建一个视图,使用户能够 CRUD Foos。

现有研究

我已阅读以下内容:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

连同以下 SO 文章
MVC4 Allowing Users to Edit List Items
MVC4 bind model to ICollection or List in partial

所以我知道如何来回传递一个 IEnumerable,问题是我想传递一些容器,其他属性包括一个 IEnumerable

要求
我希望能够绑定到这个复杂的模型,以便将它完全完整地传递给控制器​​。假设控制器只渲染视图并在发布时接收 FooController 模型。此外,我想要启用此功能所需的任何相关文章或对 View 语法的引用。

提前致谢

【问题讨论】:

  • 嘿,请描述一下 FooController 中的一种方法。
  • 也许它可以帮助:google by 'mvc4 custom binders'
  • 我正在研究 MVC4 自定义绑定器...它们看起来很酷!
  • 如果这没有帮助,请再次在 cmets 中写入。
  • 您不需要自定义模型绑定器。

标签: c# asp.net-mvc-4 razor


【解决方案1】:

这应该让你开始。

你的模特:

public class FooContainer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public IList<Foo> Foos { get; set; }
}

public class Foo
{
    public string Name {get; set; }
    public string Description {get; set;}
}

您的控制器操作:

[HttpGet]
public ActionResult Foo()
{
    var model = new FooContainer();
    return View("Foo", model);
}

[HttpPost]
public ActionResult Foo(FooContainer model)
{
    ViewBag.Test = m.Foos[1].Name;
    return View("Foo", model);
}

您的看法:

@model DriveAway.Web.Models.FooContainer

@using(Html.BeginForm()) 
{
    <p>@Html.TextBoxFor(m => m.ID)</p>
    <p>@Html.TextBoxFor(m => m.Name)</p>   

    for (int i = 0; i < 5; i++)
    {
        <p>@Html.TextBoxFor(m => m.Foos[i].Name)</p>
        <p>@Html.TextBoxFor(m => m.Foos[i].Description)</p>
    }

    <button type="submit">Submit</button>

}

@ViewBag.Test

这里发生的情况是,当您按下提交时,iList 将被发送到您的 HttpPost Foo() 操作,您可以在那里做任何您想做的事情。在我的示例中,它将显示输入到第二个名称文本框中的任何内容。您显然可以遍历每个值并检查是否已填写等。例如

foreach (var f in m.Foos)
   if (!string.IsNullOrEmpty(f.Name) && !string.IsNullOrEmpty(f.Description))
       addToDB(f); // some method to add to to a database

在视图中,我使用了for loop,限制为 5。但这显然取决于您。

【讨论】:

  • 嗨 Rudeovski,我不确定这是否是我所追求的,我会看看。我不确定这将如何传回整个容器,看起来它会将 IEnumerable 传回控制器(我已经可以开始工作了)。我想传递复杂的模型,而不仅仅是一个列表。
  • 它将把整个 FooContainer 传回来。我已将其他 2 个属性添加到视图中。所以在提交时,它会从 FooContainer 中传入 ID 和 Name,以及 Foos 的列表。
猜你喜欢
  • 2014-12-04
  • 1970-01-01
  • 2013-05-01
  • 2013-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
相关资源
最近更新 更多