Модал исчезает, когда я нажимаю для редактирования, а также идентификатор не передается в контроллер - PullRequest
0 голосов
/ 03 марта 2020

Я показываю свою разметку вида и код контроллера для справки. Я создал таблицу данных на стороне сервера и добавил функциональность кнопки «Редактировать». мой модал открывается при редактировании, но как только я нажимаю на любые значения в модале, модал исчезает.

Index.cs html:

@model IEnumerable<DapperDemo.Models.Student>

@{
    ViewBag.Title = "Index";
}

<div class="container">
    <h2>Student List</h2>
</div>

<div class="container-fluid">
        <button type="submit" id="btnDelete" class="btn btn-sm btn-danger rounded-0"><i class="fa fa-trash-o"></i> Delete</button>
        @using (Html.BeginForm("DeleteRecords", "Student", FormMethod.Post))
        {
            <table id="Student" class="ui celled table" style="width:100%">
                <thead>
                    <tr>
                        <th><input type="checkbox" name="EmpIDs" value="@ViewBag.StudentId" id="EmpIDs"></th>
                        <th>StudentId</th>
                        <th>BatchId</th>
                        <th>StudentName</th>
                        <th>RollNumber</th>
                        <th>ContactNumber</th>
                        <th>ParentContactOne</th>
                        <th>ParentContactSecond</th>
                        <th>CreatedBy</th>
                        <th></th>

                    </tr>
                </thead>
                <tbody>
                    <tr></tr>
                </tbody>

            </table>
            <div class="modal" id="myModal1" >
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header" id="ModalHeader">
                            <a href="#" class="close" data-dismiss="modal">&times;</a>

                        </div>
                        <div class="modal-body" id="myModalBodyDiv1">
                        </div>
                    </div>
                </div>
            </div>
            <input type="hidden" id="hiddenEmployeeId" />
        }

    @section scripts{
    $(document).on('click', '.edit', function () {
                    var studentId = $(this).closest('tr').find('td:eq(1)').text();
                    $.get("@Url.Action("AddEditEmployee", "Student")/" + studentId, function (data) {

                        //set Modal header text
                         $("#ModalHeader").html("Edit");

                        //add returned partial view html into modal body
                        $("#myModalBodyDiv1").html(data);

                        //show modal
                        $('#myModal1').modal('show');

                        //inititae jQuery validation
                        // $("#BlogForm").validate();

                    });
                });
            });
        </script>
    }

Я не получаю значение идентификатора студента в контроллере, хотя я передаю его через ajax.

Контроллер :

[HttpGet]  
public ActionResult AddEditEmployee(int studentId)
{
    Student student = new Student();

    using (MySqlConnection db = new MySqlConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString))
    {
        student = db.Query<Student>("SELECT * FROM student " +
                                    "WHERE studentid = " + studentId, 
                                    new { studentId }).SingleOrDefault();
    }

    return PartialView("AddEditEmployee", student);
}

// POST: Friend/Edit/5  
[HttpPost]
public ActionResult AddEditEmployee(Student student)
{
    using (MySqlConnection db = new MySqlConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString))
    {
        string sqlQuery = "update student set BatchId='" + student.BatchId + "', StudentName='" + student.StudentName + "',RollNumber='" + student.RollNumber + "',ContactNumber='" + student.ContactNumber + "' where friendid=" + student.StudentId;

        int rowsAffected = db.Execute(sqlQuery);
     }

     return Json(new { success = true, responseText = "Successfully Updated" }, JsonRequestBehavior.AllowGet);
 }

PartialView :

@model DapperDemo.Models.Student

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.StudentId)

        <div class="form-group">
            @Html.LabelFor(model => model.BatchId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BatchId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BatchId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.RollNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.RollNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.RollNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ContactNumber, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ContactNumber, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ContactNumber, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ParentContactOne, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ParentContactOne, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ParentContactOne, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ParentContactSecond, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ParentContactSecond, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ParentContactSecond, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.IsActive, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            @Html.LabelFor(model => model.CreatedBy, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.CreatedBy, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CreatedBy, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Update" class="btn btn-default" />
            </div>
        </div>
    </div>
}

1 Ответ

0 голосов
/ 03 марта 2020

Я узнал ответ, были только незначительные ошибки, я думаю, я просто заменил две строки кода в моем ajax и мой контроллер в своем контроллере, я просто возвратил представление вместо частичного представления и для передачи идентификатора, который я просто Я использовал другой метод, вот мой рабочий код, я не знаю, почему мой модал исчезал, когда я передавал его как частичное представление, которое все еще сомневается.

index.cs html


    $(document).on('click', '.edit', function () {
                    var studentId = $(this).closest('tr').find('td:eq(1)').text();
                    $.get('/Student/AddEditEmployee?studentId=' + studentId, function (data) {

                        //set Modal header text
                        // $("#ModalHeader").html("Edit");

                        //add returned partial view html into modal body
                        $("#myModalBodyDiv1").html(data);

                        //show modal
                        $('#myModal1').modal('show');

                        //inititae jQuery validation
                        // $("#BlogForm").validate();


                    });
                });

Код контроллера

    [HttpGet]
    public ActionResult AddEditEmployee(int studentId)
       {
         Student student = new Student();
         using (MySqlConnection db = new MySqlConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString))
           {
             student = db.Query<Student>("Select * From student " +
                                               "WHERE studentid =" + studentId, new { studentId }).SingleOrDefault();
           }

           return View("AddEditEmployee", student);
        }

...