Refre sh ListBox с ajax вызовом asp. net c# - PullRequest
1 голос
/ 14 апреля 2020

Этот код повторно инициализирует ListBox1 при добавлении нового элемента после Savepnusers успешно завершено.

Запись Аргентина значение в TextBox это значение равно добавлено в ListBox1

enter image description here

Но мне нужно:

  1. Хранение на столе сохранено значение Имя запись в TextBox (это работает);
  2. Добавить в ListBox1 Язык значение для Аргентина , в данном случае значение ARG в Код столбец из таблицы Страна (я не могу этого ...):

enter image description here

Есть предложения?

Мой полный код ниже.

aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs" Inherits="Default6" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
    <script type="text/javascript">

        $(function () {
            $("[id*=imgsave]").bind("click", function () {
                var qString = "?" + window.location.href.split("?")[1];
                var nnewuser = {};

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

                $.ajax({
                    type: "POST",
                    url: "Default.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));
                            if (txtUser) {
                                $("[id*=ListBox1]").append("<option value='" + nnewuser.txuser + "'>" + nnewuser.txuser + "</option>");
                            }
                        }
                    },

                    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;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txuser" runat="server" BackColor="Yellow"></asp:TextBox>
            <br />
            <br />
            <br />
            <asp:ImageButton ID="imgsave" runat="server"
                ImageUrl="/ImgFolder/Img.gif"
                OnClientClick="if (!confirm('Are you sure?')) return false;" />
            <br />
            <br />
            <br />
            <asp:ListBox ID="ListBox1" runat="server"
                SelectionMode="Multiple"
                Height="250" Width="400"></asp:ListBox>
        </div>
    </form>
</body>
</html>

cs page

using System;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;

public partial class Default6 : System.Web.UI.Page
{
    string sql;

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

        sql = @String.Format(" SELECT CountryCode FROM `countrylanguage` GROUP BY `CountryCode`; ");

        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 = "CountryCode";
                        ListBox1.DataValueField = "CountryCode";
                        ListBox1.DataSource = dt;
                        ListBox1.DataBind();
                    }
                }
                catch (OdbcException ex)
                {
                    string msg = "Fetch Error:";
                    msg += ex.Message;
                    throw new Exception(msg);
                }
                finally
                {
                    command.Connection.Close();
                }
            }
        }
    }

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

    [WebMethod(EnableSession = true)]
    [ScriptMethod]
    public static void Savepnusers(pnnusers nnewuser)
    {
        string sql = @String.Format("INSERT INTO `stored` SELECT Name, NULL FROM Country WHERE Name=?;");

        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();
                }
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            MTListBox1();
        }
    }
}

[! [Введите описание изображения здесь] [3]] [3]

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...