首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用ASP.NET MVC3编辑IEnumerable<T>?

如何使用ASP.NET MVC3编辑IEnumerable<T>?
EN

Stack Overflow用户
提问于 2010-11-21 00:50:59
回答 2查看 6.3K关注 0票数 17

给定以下类型

代码语言:javascript
复制
public class SomeValue
{
    public int Id { get; set; }
    public int Value { get; set; }
}

public class SomeModel
{
    public string SomeProp1 { get; set; }
    public string SomeProp2 { get; set; }
    public IEnumerable<SomeValue> MyData { get; set; }
}

我想为SomeModel类型创建一个编辑表单,其中包含SomeProp1SomeProp2的常用文本字段,然后创建一个表,其中包含SomeModel.MyData集合中每个SomeValue的文本字段。

这是怎么做的?如何将这些值绑定回模型?

我目前有一个表单,为每个值显示一个文本字段,但它们都具有相同的名称和Id。这显然不是有效的HTML,并且会阻止MVC将值映射回来。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-21 03:59:40

您可以使用编辑器模板来完成此操作。这样,框架将处理所有事情(从正确命名输入字段到正确绑定post操作中的值)。

控制器:

代码语言:javascript
复制
public class HomeController : Controller
{
    public ActionResult Index()
    {
        // In the GET action populate your model somehow
        // and render the form so that the user can edit it
        var model = new SomeModel
        {
            SomeProp1 = "prop1",
            SomeProp2 = "prop1",
            MyData = new[] 
            {
                new SomeValue { Id = 1, Value = 123 },
                new SomeValue { Id = 2, Value = 456 },
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SomeModel model)
    {
        // Here the model will be properly bound
        // with the values that the user modified
        // in the form so you could perform some action
        return View(model);
    }
}

视图(~/Views/Home/Index.aspx):

代码语言:javascript
复制
<% using (Html.BeginForm()) { %>

    Prop1: <%= Html.TextBoxFor(x => x.SomeProp1) %><br/>
    Prop2: <%= Html.TextBoxFor(x => x.SomeProp2) %><br/>
    <%= Html.EditorFor(x => x.MyData) %><br/>
    <input type="submit" value="OK" />
<% } %>

最后是编辑器模板(~/Views/Home/EditorTemplates/SomeValue.ascx),它将为MyData集合的每个元素自动调用:

代码语言:javascript
复制
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.SomeValue>" %>
<div>
    <%= Html.TextBoxFor(x => x.Id) %>
    <%= Html.TextBoxFor(x => x.Value) %>
</div>
票数 14
EN

Stack Overflow用户

发布于 2010-11-21 01:51:35

IList实现了IEnumerable,因此您可以像这样修改模型:

代码语言:javascript
复制
public class SomeModel {
    public string SomeProp1 { get; set; }
    public string SomeProp2 { get; set; }
    public IList<SomeValue> MyData { get; set; }
}

您可以使用IModelBinder接口为您的特定模型创建活页夹。有几种方法可以做到这一点。您可以为模型创建一个EditorFor cshtml,它将遍历您的SomeValue列表并输出适当的ids等等。然后,在您的ModelBinder实现中,您将读取您的in并适当地绑定它们。我可以在一段时间内发布一个工作样本。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4233832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档