12

I have following Ajax call method and The asp.net webmethod.

My asp.net function is returning some values I need those back in Ajax call ..

I have tried lot of things but not succeded yet.

AJAX CALL

<script type="text/javascript">


        $(document).ready(function () {
            // Add the page method call as an onclick handler for the control.
            $("#<%=ddlEmailTemplate.ClientID%>").change(function () {
                debugger;
                var myparam = $("#<%=ddlEmailTemplate.ClientID%>").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)
                    }
                });
            });
        });
    </script>

WebMethod asp.net

Updated after your answer

[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 ;
8
  • Have you checked in success function what data provides alert(data); Commented Mar 7, 2017 at 12:13
  • @RonyLoud I am not able to return something from webmethod so success is null Commented Mar 7, 2017 at 12:15
  • you need to provide dataType:'JSON' as you are expecting json in your data and check alert(data.subject) Commented Mar 7, 2017 at 12:19
  • But how can I return value of subject here ? that is the issue Commented Mar 7, 2017 at 12:21
  • JsonConvert.SerializeObject(new { subject = subject, description = Description }) here you are sending Class as Json object which is received in data Commented Mar 7, 2017 at 12:22

3 Answers 3

21

Include 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

<div> 
     <input type="text" name="name" id="txtname"/>
     <input type="text" name="age" id="txtage"/>
     <input type="button" id="btnSubmit" value="details"/>
</div>

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);
            });
        });
Sign up to request clarification or add additional context in comments.

1 Comment

I found this code useful but needed to make the url: argument a relative path so I'll include this link in case it helps others: stackoverflow.com/questions/5092352/…
1

To return a JSON object you need to serialize your response. In your method return something like return JsonConvert.SerializeObject(new { subject = subject, description = Description }); You will need to add a using statement at the top for using Newtonsoft.Json;.

In order to avoid errors about using unassigned variables, you will need to give your subject and Description variables starting values like `string subject = "". That way if they do not get a new value, they return empty strings.

Instead of creating a generic object of new { subject = subject, description = Description }, you could indeed create a class containing those properties:

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

And then serialize it the same way above: JsonConvert.SerializeObject(new EmailTemplate{ subject = subject, description = Description }); But if you aren't going to use that model class anywhere else, it isn't necessary.

Finally, in your JavaScript, you should be able to access the data like this:

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

1 Comment

I have updated my question with your given code , Please take a look.. But now error is for subject and Description use of unassigned local variable
-1

You may return Json(Your_object) function. But you have to change your method signature to return IHttpActionResult. An use model to return values. For example:

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

Then your return instruction will look like

return Json(emailModel);

1 Comment

IHttpActionResult is for WebAPI, not Webmethods inside aspx pages. This answer is talking about the wrong technology

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.