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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- ASP.NET MVC 3 – 如何以有效的方式限制区域?
- asp.net viewstate加密问题
- asp.net-mvc – 用于asp.net的rails样式数据库迁
- asp.net – 为什么我需要PUT或DELETE Http Verbs
- 使用ASP.NET构建了多少个公共高流量网站?
- 实现不要在asp.net mvc中跟踪
- asp.net-mvc – 如何gzip内容在asp.net MVC?
- asp.net-mvc – 为什么我的ViewModel在[HttpPost
- ASP.NET Core使用TopShelf部署Windows服务
- asp.net-mvc – 针对移动应用的REST API的OAuth
热点阅读