如何编辑一个IEnumerable< T>在ASP.NET MVC 3? [英] How do I edit an IEnumerable<T> with ASP.NET MVC 3?

查看:286
本文介绍了如何编辑一个IEnumerable< T>在ASP.NET MVC 3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下几种类型

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 这将包含普通的文本字段 SomeProp1 创建一个编辑的形式和 SomeProp2 ,然后包含每个文本字段的表 someValue中 SomeModel.MyData 集合。

I want to create an edit form for the type SomeModel which would contain the usual text fields for SomeProp1 and SomeProp2 and then a table containing a text field for each SomeValue in the SomeModel.MyData collection.

这是怎么做的?如何值坐上开往回模式?

How is this done? How do the values get bound back to the model?

我现在有一个表格显示的文本字段为每个值,但它们都具有相同的名称和标识。这显然​​不是有效的HTML,将prevent MVC从映射值了。

I currently have a form displaying a text field for each value but they all have the same name and same Id. This is obviously not valid HTML and will prevent MVC from mapping the values back.

推荐答案

您会使用编辑器模板做到这一点。这样的框架会照顾一切(从正确的命名输入字段正确绑定值回后的动作)。

You would do it using Editor Templates. This way the framework will take care of everything (from properly naming the input fields to properly binding the values back in the post action).

控制器:

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

查看(〜/查看/首页/的Index.aspx ):

<% 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" />
<% } %>

最后编辑模板(〜/查看/首页/ EditorTemplates / SomeValue.ascx ),这会为每个元件自动调用迈德特系列:

And finally the Editor Template (~/Views/Home/EditorTemplates/SomeValue.ascx) which will be automatically invoked for each element of the MyData collection:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.SomeValue>" %>
<div>
    <%= Html.TextBoxFor(x => x.Id) %>
    <%= Html.TextBoxFor(x => x.Value) %>
</div>

这篇关于如何编辑一个IEnumerable&LT; T&GT;在ASP.NET MVC 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆