どうしていただくために、辞書のパラメータとして、ActionResult方法からjQuery/Ajax?

StackOverflow https://stackoverflow.com/questions/1077481

質問

私はjQueryを使うには、Ajaxを利用した通話を、HttpポストASP.NET MVC.すればよいのでしょうかを通過でき辞書の値です。

最も近いものを思いったパス多次元配列の文字列があるが、実際に取得したActionResult方法は、単元を含む文字列配列文字列を連結した文字列のキーと値のペアにします。

のためのインスタンスの最初の項目は、以下の"価値"が配列は以下の値:

"id,200"

以下に例を示しますのActionResult方法

public ActionResult AddItems(string[] values)
{
    // do something
}

こちらは、どのように私は、以下のメソッドを呼び出しからjQuery:

$.post("/Controller/AddItems",
    {
        values: [
            ["id", "200"],
            ["FirstName", "Chris"],
            ["DynamicItem1", "Some Value"],
            ["DynamicItem2", "Some Other Value"]
        ]
    },
    function(data) { },
    "json");

なんだろうけど、日本人の受け渡し方法の辞書オブジェクトからのjQueryをActionResult法の代わりに配列?

ように定義しっActionResultようになります:

public ActionResult AddItems(Dictionary<string, object> values)
{
    // do something
}

ご意見募集

更新: また通コンマでの値では基本的にだけるので、実際に構文解析のキーと値のペアを使用文字列の構文解析.

この:

values: [
    ["id", "200,300"],
    ["FirstName", "Chris"]
]

この:

values[0] = "id,200,300";
values[1] = "FirstName,Chris";
役に立ちましたか?

解決

かきっかけになるかもしれないとね!!を提案す。私は最後に把握し、最善の解決策であpass JSONのHttpポスト用カスタムModelBinderに変換するJSONを辞書で調べました。ひとつわかった私の溶液を作成しJsonDictionaryオブジェクトを継承したから辞書のように取付けることができ、カスタムModelBinderのJsonDictionaryタイプは、そもそも太陽系が紛争の未来を利用した場合、辞書としてActionResultパラメータを与えた後で異なる目的によJSON.

こちらは最終ActionResult方法

public ActionResult AddItems([Bind(Include="values")] JsonDictionary values)
{
    // do something
}

のjQuery"$.ポスト"。

$.post("/Controller/AddItems",
{
    values: Sys.Serialization.JavaScriptSerializer.serialize(
            {
                id: 200,
                "name": "Chris"
            }
        )
},
function(data) { },
"json");

その後、JsonDictionaryModelBinderを選択する必要がある、あるいはこのApplication_Start法による。asax.cs:

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(JsonDictionary), new JsonDictionaryModelBinder());
}

と、いよいよこのJsonDictionaryModelBinderオブジェクトJsonDictionaryオブジェクトで作成した:

public class JsonDictionary : Dictionary<string, object>
{
    public JsonDictionary() { }

    public void Add(JsonDictionary jsonDictionary)
    {
        if (jsonDictionary != null)
        {
            foreach (var k in jsonDictionary.Keys)
            {
                this.Add(k, jsonDictionary[k]);
            }
        }
    }
}

public class JsonDictionaryModelBinder : IModelBinder
{
    #region IModelBinder Members

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.Model == null) { bindingContext.Model = new JsonDictionary(); }
        var model = bindingContext.Model as JsonDictionary;

        if (bindingContext.ModelType == typeof(JsonDictionary))
        {
            // Deserialize each form/querystring item specified in the "includeProperties"
            // parameter that was passed to the "UpdateModel" method call

            // Check/Add Form Collection
            this.addRequestValues(
                model,
                controllerContext.RequestContext.HttpContext.Request.Form,
                controllerContext, bindingContext);

            // Check/Add QueryString Collection
            this.addRequestValues(
                model,
                controllerContext.RequestContext.HttpContext.Request.QueryString,
                controllerContext, bindingContext);
        }

        return model;
    }

    #endregion

    private void addRequestValues(JsonDictionary model, NameValueCollection nameValueCollection, ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        foreach (string key in nameValueCollection.Keys)
        {
            if (bindingContext.PropertyFilter(key))
            {
                var jsonText = nameValueCollection[key];
                var newModel = deserializeJson(jsonText);
                // Add the new JSON key/value pairs to the Model
                model.Add(newModel);
            }
        }
    }

    private JsonDictionary deserializeJson(string json)
    {
        // Must Reference "System.Web.Extensions" in order to use the JavaScriptSerializer
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Deserialize<JsonDictionary>(json);
    }
}

他のヒント

こうしてみました。保存するJavascript:

  var dict = {};       
        dict["id"] = "200";
        dict["FirstName"] = "Chris";
        dict["DynamicItem1"] = "Some Value";
        dict["DynamicItem2"] = "Some Other Value";

        var theObject = {};
        theObject.dict = dict;
        $.post(URL, theObject, function (data, textStatus, XMLHttpRequest) {
            console.log("success");
        }, "json");

行動方法

public ActionResult MethodName(DictionaryModel obj)
    {
       //Action method logic
    }

public class DictionaryModel
{
    public Dictionary<string, string> dict { get; set; }

}

できるカスタムモデルのバインダーや浄が可能です。裏-まだに手動ででもかまいませんが、結局(Request.形を解析しの文字列を辞書にトラララ)ですが、少なくとも-コントローラするクリーンコードする再利用可能な別の行動します。

いと思うので辞書からjQuery/AjaxへのActionResult法については、Httpます。ひとつのきっかけになるかもしれないと行う最も簡単な作業で渡されるJSONオブジェクトとして構文解析することとして提出してください。

こちらは、修理技術のデモンストレーションの呼び出し"$.ポスト"からのjQueryをJSONとして、擬似文字列のコピーや辞書

$.post("/Controller/AddItems",
    {
        values: Sys.Serialization.JavaScriptSerializer.serialize(
                {
                    id: 200,
                    "name": "Chris"
                }
            )
    },
    function(data) { },
    "json");

は"Sys.直列化します。JavaScriptSerializer.serialize"機能する方法にASP.NET AJAXでのJavaScriptライブラリ。

こちらは、修理技術のデモンストレーションのActionResult方法

public ActionResult AddItems(Dictionary<string, object> values)
{
    // Must Reference "System.Web.Extensions" in order to use the JavaScriptSerializer
    var json = new System.Web.Script.Serialization.JavaScriptSerializer();
    var data = json.Deserialize<Dictionary<string, string>>(routeValues);

    // do something
}

と思うことが容易になりユニット試験による通JSONを使わずに形コレクションの送信/検索のキーと値のペアになっています。まく働くようにカスタムIModelBinder、カスタムIModelBinderな問題とその他のActionResult方法がこの処理はジョルテではなくいのではないかと思います。

DefaultModelBinder動きを拘束するポストを配列または辞書で調べました。例えば:

配列の場合:

public ActionResult AddItems(string[] values)

$.post("/Controller/AddItems", { values: "values[0]=200&values[1]=300" },
    function(data) { }, "json");

または:

$.post("/Controller/AddItems", { values: "values=200&values=300" },
    function(data) { }, "json");

のための辞書

public ActionResult AddItems(Dictionary<string, object> values)

$.post("/Controller/AddItems", {
    values: "values[0].Key=value0&values[0].Value=200&values[1].Key=value1&values[1].Value=300" }, function(data) { }, "json");

更新:

の場合の値は、HTMLの入力をマウスでクリックいつものようになります:

var postData = $('input#id1, input#id2, ..., input#idN").serialize();
// or
var postData = $('input.classOfYourInputs").serialize();

$.post("/Controller/AddItems", { values: postData }, function(data) { }, "json");

更新:

またチェックす: スコットHanselmanのComputerZen.com -ASP.NET ワイヤー形式のためのモデルを結合する配列リスト、コレクション、辞書

市中心にあるこの投稿ができないながらの挨拶。

@eu-ge-ne:"DefaultModelBinder動きを拘束するポストを配列または辞書で調べました。" Trueしかし、少なくとも辞書を見たいのに必要な書記法は直感的には.

@Chris:昨日、私は同じ問題をできるようにJavaScript(JSON)辞書をコントローラのアクション方法です。また、完全に異なるカスタムモデルのバインダーとプロセス一般の辞書と異なる型の引数になります。またまMVC3かったのを改善。

の詳細については私の経験や、ソースコードのカスタムモデルのバインダーの、ご自由にお使いくださいブログで http://buildingwebapps.blogspot.com/2012/01/passing-javascript-json-dictionary-to.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top