0

I have web page with dropdown list "ListBox" with email address of users.

How do I make a function that update the dropdownlist "ListBox" everytime when I add new email user in the dropdown list ?

I have trying this solution without success because the dropdown list it emptied, instead of add new user.

This is my code :

    nnewuser.txuser = $("[id*=txuser]").val();

    $.ajax({
        type: "POST",
        url: "prefix.aspx/Savepnusers" + qString,
        data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function (response) {
            if ($("[id*=txuser]").val()) {
                alert("Ok");
                alert(JSON.stringify(nnewuser));
                $("[id*=ListBox1]").html(response);                            
            }
        },

        failure: function (response) {
            alert(response.d);
        },

        error: function (response) {
            alert(response.d);
        },

        error: function (xhr, ajaxOptions, thrownError) {
            alert("error : " + thrownError + JSON.stringify(nnewuser));
        }
    });
    return false;
});

Savepnusers

public class pnnusers
{
    public string txuser { get; set; }
}

[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnusers(pnnusers nnewuser)
{
    string sql = @String.Format(" INSERT INTO `tbl_email` (email) VALUES (?); ");

    using (OdbcConnection cn =
      new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
    {
        using (OdbcCommand command =
                new OdbcCommand(sql, cn))
        {
            try
            {
                command.Connection.Open();
                command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                command.Connection.Close();
            }
        }
    }
}

DropDownList

private void MTListBox1()
{
    DataTable dt = new DataTable();

    sql = @String.Format(" SELECT ");
    sql += String.Format(" LOWER(Email) AS UserEmail ");
    sql += String.Format(" FROM ");
    sql += String.Format("  tbl_email ORDER BY LOWER(Email) ASC; ");

    using (OdbcConnection cn =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
    {
        using (OdbcCommand command =
            new OdbcCommand(sql, cn))
        {
            try
            {
                command.Connection.Open();
                OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
                sqlDa.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    ListBox1.DataTextField = "UserEmail";
                    ListBox1.DataValueField = "UserEmail";
                    ListBox1.DataSource = dt;
                    ListBox1.DataBind();
                }
            }
            catch (OdbcException ex)
            {
                string msg = "Fetch Error:";
                msg += ex.Message;
                throw new Exception(msg);
            }
            finally
            {
                command.Connection.Close();
            }
        }
    }
}
6
  • What is not working exactly? Do you get any error or something? And could you add your Savepnusers method too? Commented Apr 14, 2020 at 7:27
  • @SelimYıldız Ok, the Savepnusers added in first question Commented Apr 14, 2020 at 7:32
  • Your method does not return anything so you can't use response in ajax. How can you initialize your ListBox1? I suggest you that after calling Savepnusers method re-initialize your dropdownlist. Commented Apr 14, 2020 at 7:36
  • @SelimYıldız How to do this ? Any example please ? Commented Apr 14, 2020 at 7:51
  • I can provide an solution but I need to see how do you initialize your dropdownlist. Could you please add that? Commented Apr 14, 2020 at 8:23

1 Answer 1

0

There are 2 main problems here:

First, your Savepnusers method does not return anything, so you can't use response in AJAX calls. What you need is that re-initialize ListBox1 or append new item after Savepnusers complete successfully:

Secondly, it seems you can't send nnewuser as parameter correctly. You don't need to have pnnusers class instead just use string type as a parameter.

So server-side:

public static void Savepnusers(string nnewuser)

On client-side, you need to add dropdownlist item with jquery:

var txtUser = $("[id*=txuser]").val();
$.ajax({
        type: "POST",
        url: "prefix.aspx/Savepnusers",
        data: JSON.stringify({ nnewuser: txtUser }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",

        success: function () {
            //Since you can't use response object, you can append new item  to dropdownlist
            if (txtUser) {
               $("[id*=ListBox1]").append('<option value="'+txtUser+'">'+txtUser+'</option>');         
            }

        },

        failure: function (response) {
            alert(response.d);
        },

        error: function (response) {
            alert(response.d);
        },

        error: function (xhr, ajaxOptions, thrownError) {
            alert("error : " + thrownError + JSON.stringify(nnewuser));
        }
    });

See: asp dropdownlist dynamic value from javascript issue

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for help, really appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.