WebMethodから返されたときに、オブジェクトを適切に処理するのに苦労しています。条件(その後の私の研究):
プロパティを保持するための単純なクラス:
public class memberLogin
{
public string Username {get; set;}
public string Password {get; set;}
}
シリアル化方法:
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
}
(わかりやすくするために簡略化)Webmethod
[WebMethod(EnableSession = true)]
public static string getCredentials()
{
memberLogin ml = new memberLogin();
ml.Username = "user";
ml.Password = "pass";
string json = JsonHelper.JsonSerializer<memberLogin>(ml);
return json;
}
return null;
}
そしてJavaScript
$("#element").live("click", function (e) {
$.ajax({
type: "POST",
url: "Default.aspx/getCredentials",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: post_to_url
});
});
function post_to_url(params) {
method = "post";
path = "http://example";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
デバッグ時にWebMethodが返さ"{\"Password\":\"pass\",\"Username\":\"user\"}"
れるので、それが私が望むもの(key、value par)であるように見えます\
が、それがシリアル化される方法です。ただし、ajaxを使用して取得した場合、値を取得できません。alert(params)
を与えるobject Object
、params.Usernameを呼び出す。を与えるundefined
。足りないものはありますか?ある種のキャスト?オブジェクトがシリアル化されていれば、そのような必要はないと思いました。非常に長い投稿で申し訳ありませんが、私はできるだけ多くの情報を提供しようとしました。