将Json对象从Asp.net webMethod返回到Ajax调用

我有以下Ajax调用方法和asp.net webmethod。

我的asp.net函数返回一些我在Ajax调用中需要的值。

我已经尝试过很多东西,但还没有成功。

AJAX CALL

 $(document).ready(function () { // Add the page method call as an onclick handler for the control. $("#").change(function () { debugger; var myparam = $("#").val(); //id name for dropdown list $.ajax({ type: "POST", url: "FileTax.aspx/ddlEmailTemplate_SelectedIndexChanged", data: '{param:"' + myparam + '"}', contentType: "application/json; charset=utf-8", success: function (data) { alert(data.d) } }); }); });  

WebMethod asp.net

答案后更新

 [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)] public static string ddlEmailTemplate_SelectedIndexChanged(string param) { string subject; string Description; using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ForMyTaxConnectionString"].ConnectionString)) { con.Open(); DataSet ds = new DataSet(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = con; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "Spo_ShowEmailTemplateContent"; cmd.Parameters.Add(new SqlParameter("@Tid", SqlDbType.Int)).Value = Convert.ToInt32(param); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(ds); con.Close(); da.Dispose(); } if (ds.Tables[0].Rows.Count > 0) { DataRow dr = ds.Tables[0].Rows[0]; subject = Convert.ToString(dr["TemplateSubject"]); Description = Convert.ToString(dr["TemplateDescription"]); } } } return JsonConvert.SerializeObject(new { subject = subject, description = Description }); // return subject ; 

包括using Newtonsoft.Json;

CS

 public string CheckDetails(string param1, string param2) { var chk = new check { subject = "hello! " +param1 , description = param2 +" Years Old" }; return JsonConvert.SerializeObject(chk); } public class check { public string subject { get; set; } public string description { get; set; } } 

HTML

 

jQuery的

 $(function () { $('#btnSubmit').on('click', function () { var options = { type: "POST", url: '/Ajax/CheckDetails/', data: '{param1:"' + $('#txtname').val() + '",param2:"' + $('#txtage').val() + '"}', async: false, cache: false, dataType: "json", contentType: "application/json; charset=utf-8", success: function (response) { if (response != null && response.d != null) { var data = response.d; alert(typeof (data)); //it comes out to be string //we need to parse it to JSON data = $.parseJSON(data); alert(data.subject); alert(data.description); } } }; $.ajax(options); }); }); 

要返回JSON对象,您需要序列化您的响应。 在你的方法中返回类似return JsonConvert.SerializeObject(new { subject = subject, description = Description }); 您需要在顶部添加using语句才能using Newtonsoft.Json;

为了避免使用未分配变量的错误,您需要为subjectDescription变量提供类似`string subject =“”的值。 这样,如果他们没有获得新值,他们将返回空字符串。

您可以创建一个包含这些属性的类,而不是创建new { subject = subject, description = Description }的通用对象:

 public class EmailTemplate { public string Subject { get; set; } public string Description { get; set; } } 

然后按照上面相同的方式序列化它: JsonConvert.SerializeObject(new EmailTemplate{ subject = subject, description = Description }); 但如果您不打算在其他任何地方使用该模型类,则没有必要。

最后,在您的JavaScript中,您应该能够访问如下数据:

 success: function (data) { console.log("Subject:" + data.subject); console.log("Description:" + data.description); } 

您可以return Json(Your_object)函数。 但是你必须改变你的方法签名才能return IHttpActionResult 。 用于返回值的使用模型。 例如:

 public class EmailModel { public string TemplateSubject {get;set;} public string TemplateDescription {get;set;} } 

然后你的返回指令看起来像

 return Json(emailModel);