asp.net MVC 3 C#后数组变量 [英] asp.net mvc 3 c# post array of variables
问题描述
我需要通过数组POST方法。但我显然缺少sometging
我的观点是这个样子:
I need to pass array to POST method. But i'm obviously missing sometging My view look something like this:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Klausimynas.Models.Rezultat>" %>
<input type="text" name="x[1]">
<input type="text" name="x[2]">
<input type="text" name="x[3]">
<input type="text" name="x[4]">
<input type="text" name="x[5]">
<input type="text" name="x[6]">
<input type="text" name="x[7]">
我的方法的声明看起来是这样的:
My method declaration looks like this:
[HttpPost]
public ActionResult LetsTest(IEnumerable<Rezultat> rez)
当我试图提取数据,我得到的价值不能为空。
什么我失踪?
and when i'm trying to extract data i'm getting Value can't be null. What i'm missing?
推荐答案
有几件事情错在这里:
- 您的视图类型为
Rezultat
但是你要处理的模型作为的IEnumerable&LT; Rezultat&GT;
- 您正在尝试每个文本框
X [I]
绑定 - 这将等同于Model.x [I]
- 当你真正想要的是将其绑定到[I] .X
(即模型[I] .X
)。
- Your view is typed to
Rezultat
but you're trying to treat the model as anIEnumerable<Rezultat>
. - You're trying to bind each textbox to
x[i]
- which would be equivalent toModel.x[i]
- when what you really want is to bind it to[i].x
(i.e.Model[i].x
).
因此,要解决这个问题,你需要改变一些事情。
So, to correct this, you need to change a couple of things.
首先,改变你的看法继承 System.Web.Mvc.ViewPage&LT;&IEnumerable的LT; Klausimynas.Models.Rezultat&GT;&GT;
。现在你的观点可以传递一个的IEnumerable&LT; Rezultat方式&gt;
,这是你的控制器动作需要什么
First, change your view to inherit System.Web.Mvc.ViewPage<IEnumerable<Klausimynas.Models.Rezultat>>
. Now your view can pass an IEnumerable<Rezultat>
, which is what your controller action expects.
二,更改此:
<input type="text" name="x[0]">
要这样:
<input type="text" name="[0].x">
这样做的理由是,首先会尝试将值绑定Model.x [0]
,这是(或将是,一旦你输入你的观点正确),相当于第一元素属性 X
的一个实例的IEnumerable&LT; Rezultat&GT;
。这显然是不完全正确,为的IEnumerable
公开没有财产 X
。你想要的是绑定模型[0] .X
,这是<$ C $的财产 X
C> Rezultat 在索引对象 0
。
The reason for this is that the first will attempt to bind the value to Model.x[0]
, which is (or will be, once you've typed your view properly) equivalent to the first element in property x
of an instance of IEnumerable<Rezultat>
. This obviously isn't quite right, as an IEnumerable
exposes no property x
. What you want is to bind Model[0].x
, which is the property x
of the Rezultat
object at index 0
.
更妙的是,使用一个助手为您生成的名称:
Better still, use a helper to generate the name for you:
for(int i=0; i < Model.Count; i++)
{
@Html.TextBoxFor(m => m[i].x)
}
这篇关于asp.net MVC 3 C#后数组变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!