Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 c# post array of variables

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple of things wrong here:

  1. Your view is typed to Rezultat but you're trying to treat the model as an IEnumerable<Rezultat>.
  2. You're trying to bind each textbox to x[i] - which would be equivalent to Model.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.

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.

Second, change this:

<input type="text" name="x[0]">

To this:

<input type="text" name="[0].x">

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...