Невозможно отправить данные в базу данных с помощью модального всплывающего окна Bootstrap в веб-формах asp.net - PullRequest
0 голосов
/ 30 октября 2018

Я использую веб-формы asp.net и хочу опубликовать данные из модального всплывающего окна в базе данных, это не работает, но я просто помещаю текстовые поля в теле страницы содержимого, чтобы сохранять данные просто отлично, я Мне нужно использовать модальные всплывающие окна, поскольку все проекты, которые я хочу сделать, требуют этого мой код выглядит следующим образом

<script type="text/javascript">

    $(document).ready(function () {

        insertkpi();
    });


    function insertkpi() {
        $('#savebtn').click(function () {
            var kpi = {};
            kpi.Name = $('#TextBox1').val();
            kpi.initiative = $('#TextBox2').val();
            kpi.perfomance = $('#TextBox3').val();
            kpi.progress = $('#TextBox4').val();
            kpi.BaseTarget = $('#TextBox5').val();
            kpi.streachTarget = $('#TextBox6').val();
            kpi.Period = $('#TextBox7').val();

            $.ajax({
                url: 'addKpi.aspx/submitkpi',
                method: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: '{item: ' + JSON.stringify(kpi) + '}',
                success: function () {
                    displayKPI();

                },

                error: function (xhr, status, p3, p4) {
                    console.debug(xhr);
                    var err = "Error " + " " + status + " " + p3;
                    if (xhr.responseText && xhr.responseText[0] == "{")
                        err = JSON.parse(xhr.responseText).message;
                    alert(err);
                }

            });
        });
    }


</script>

модальный div

 <div class="modal" id="kpimodal" data-keyboad="false" data-backdrop="static" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">New KPI</h4>
                <button class="close" data-dismiss="modal">&times;</button>
                </div>
            <div class="modal-body" id="subdata">

                <div class="form-group">
                    <label id ="namlb">Name</label>
                    <input type="text" class="form-control" runat="server" placeholder ="name" id="nametxt" />
                </div>
                <div class="form-group">
                    <label id ="inlb">Initiative</label>
                    <input type="text" class="form-control" runat="server" placeholder ="initiative" id="inittxt" />
                </div>
                <div class="form-group">
                    <label id ="perflb">Perfomance</label>
                    <input type="text" class="form-control" runat="server" placeholder ="perfomance" id="perftxt" />
                </div>
                <div class="form-group">
                    <label id ="proglb">Progress</label>
                    <input type="text" class="form-control" runat="server" placeholder ="progress" id="progtxt" />
                </div>
                <div class="form-group">
                    <label id ="baselb">Base Target</label>
                    <input type="text" class="form-control" runat="server" placeholder ="base Target" id="basetxt" />
                </div>
                <div class="form-group">
                    <label id ="streachlb">Streach Target</label>
                    <input type="text" class="form-control" runat="server" placeholder ="streach target" id="strtxt" />
                </div>
                <div class="form-group">
                    <label id ="perlb">Target Period</label>
                    <input type="text" class="form-control" runat="server" placeholder ="Period" id="periodtxt" />
                </div>

                </div>
            <div class="modal-footer">
                <button class="btn-primary" runat="server" id="savebtn">Save</button>
                <button class="btn-primary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
    </div>

Введите новый KPI

веб-метод в веб-сервисе

 [WebMethod]
    public static string submitkpi(insertkpi item)
    {
        string constring = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO KPIs (Name,Initiative,perfomance,progress,BaseTarget,streachTarget,Period) Values(@Name,@Initiative,@perfomance,@progress,@BaseTarget,@streachTarget,@Period)", conn))
            {
                try
                {
                conn.Open();
                cmd.Parameters.AddWithValue("@Name", item.Name);
                cmd.Parameters.AddWithValue("@Initiative", item.Initiative);
                cmd.Parameters.AddWithValue("@perfomance", item.perfomance);
                cmd.Parameters.AddWithValue("@progress", item.progress);
                cmd.Parameters.AddWithValue("@BaseTarget", item.BaseTarget);
                cmd.Parameters.AddWithValue("@streachTarget", item.streachTarget);
                cmd.Parameters.AddWithValue("@Period", item.Period);


                cmd.ExecuteNonQuery();
                }
                catch (Exception )
                {

                }
                finally
                {
                    conn.Close();
                }

            }
        }

Ответы [ 2 ]

0 голосов
/ 30 октября 2018

JSON.stringfy не кажется мне подходящим, вы получите недействительный json, попытайтесь вот так

 $.ajax({
            url: 'addKpi.aspx/submitkpi',
            method: 'POST',
            contentType: 'application/json; charset=utf-8',
            data:  JSON.stringify({item:kpi}),
            success: function () {
                displayKPI();

            },
0 голосов
/ 30 октября 2018

В вашем объекте kpi у вас есть kpi.name set = $("#Textbox1").val(). Однако, это не существует в вашем модале. Для вашего текстового поля имени в вашем модале идентификатор nametxt. Поэтому используйте kpi.name = $("#nametxt").val(); для создания вашего объекта.

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