.NET MVC剃刀动态表单生成 [英] .NET MVC Razor Dynamic Form Generation

查看:269
本文介绍了.NET MVC剃刀动态表单生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建设MVC网站,我传递给我的查看视图模型包含了一个自定义对象又包含自定义对象的名单IEnumarable

I'm building a site in MVC and the View Model I am passing to my View contains a custom object which in turn contains an IEnumarable list of custom objects.

的想法是,剃刀将动态生成了IEnumerable形式,其可以是任何数目的对象。

The idea is that razor will dynamically generate the form for the IEnumerable which could be any number of objects.

@foreach (var data in Model.Kpi.Values)
{
   <div class="editor-label">
       @Html.Label(data.Field.Name);
   </div>
   <div class="editor-field">
       @Html.EditorFor(model => data.Value)
       @Html.ValidationMessageFor(model => data.Value)
   </div>
}

的形式完美地显示包括数据注解但是IEnumerable的是在控制器的功能后空。

The forms display perfectly including the data annotations however the IEnumerable is null in the controllers post function.

[HttpPost]
public virtual ActionResult Create(KpiCreateViewModel vm)
{
    return this.RedirectToAction(MVC.Kpi.Index());
}

我把一个破发点上return语句和检查虚拟机变量的内容。

I've put a break point on the return statement and inspected the contents of the vm variable.

任何人都可以提出一个方法来检索表单数据?

Can anyone suggest a method to retrieve the form data?

在此先感谢

推荐答案

这是因为 EditorFor 方法没有足够的信息来生成可以通过使用一个名称在 DefaultModelBinder 当你回发。再看那就是在HTML生成的name属性。从您传递的前pression生成的名字,但你不必完整路径在循环中的属性。

It's because the EditorFor method doesn't have enough information to generate a name that can be used by the DefaultModelBinder when you post back. Look at the name attribute that is being generated in the HTML. The name is generated from the expression that you pass in, but you don't have to full path to the property in the loop.

将其更改为索引循环,它的的工作。

Change it to an indexed loop and it should work.

@for(var i=0; i<Model.Kpi.Values.Count(); i++)
{
   <div class="editor-label">
       @Html.Label(model.Kpi.Values[i].Field.Name);
   </div>
   <div class="editor-field">
       @Html.EditorFor(model => model.Kpi.Values[i].Value)
       @Html.ValidationMessageFor(model => model.Kpi.Values[i].Value)
   </div>
}

这篇关于.NET MVC剃刀动态表单生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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