加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何使用ASP.NET MVC 3编辑IEnumerable?

发布时间:2020-12-16 00:32:18 所属栏目:asp.Net 来源:网络整理
导读:给出以下类型 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 IEnumerableSomeValue MyData { get; s
给出以下类型
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的通常文本字段,然后包含SomeModel.MyData集合中每个SomeValue的文本字段的表。

这怎么做?这些价值观如何回归到模型?

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

解决方法

您将使用编辑器模板来执行此操作。这样,框架将处理所有内容(从命名输入字段到在后期操作中正确绑定值)。

控制器:

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):

<% 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集合的每个元素:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读