0

座標を含む配列をMVCコントローラーに送信しようとしています(すべてのコードを投稿するのではなく、関連するものだけを投稿します)。

var coords = [];
..for loop
    coords.push({ X: x, Y: y});
..end of loop

次に、次のオブジェクトをデータとして使用してajax呼び出しを実行します

var data = {
    OtherData: "SomeString",
    OtherData2: 1,
    Coords: coords
};

コントローラでアクションをデバッグすると、他のデータが正しく解析されます。期待するモデルは次のようになります。

public class Model
{
    public int OtherData2 { get; set; }
    public string OtherData { get; set; }
    public Point[] Coords { get; set; }
}

私がすでに試したこと-リストの使用-プロパティとしてXとYを使用してクラスSimplePointを作成する-文字列値としてX値とY値を送信する-1文字列として連結されたX値とY値を送信し、文字列のリストを受信する

配列としてのポイントオブジェクトの場合、同じ数のポイントを持つリストを取得しますが、Listオブジェクトではすべて空(0,0)であり、リストはnullになりますか?

おそらく重要な注意点は、MVC4を使用しているということです

4

1 に答える 1

0

DefaultModelBinder はリストにバインドする方法を認識していないようです
(適切な型コンバーターがありません) 独自のポイントとそれに型コンバーターを作成することができます:

[TypeConverter(typeof(PointTypeConverter))]
public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
}

/// <summary>
/// we need this so we can use the DefaultModelBinder to bind to List<Point>
/// example at http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx
/// </summary>
public class PointTypeConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return true;
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Point ret = serializer.Deserialize<Point>((string)value);
        return ret;
    }

}

コントローラーのアクションは次のようになります。

[HttpPost]
public ActionResult testPoints(List<Point> cords)
{
    //party
}

Ajax 呼び出しは次のようになります。

$.ajax({
url: "/Home/testPoints/",
type: "POST",
data: {
            //note that i stringify very value in the array by itself
    cords: [JSON.stringify({'X':1,'Y':2}),JSON.stringify({'X':3,'Y':4})]
},
success: function (data)
{
    //client party
}
});

これらすべてをMVC3でテストしましたが、MVC4で機能しない理由はありません

于 2012-05-01T11:01:45.630 に答える