ASP. Net Core MVC CRUD PopUp Modal - PullRequest
0 голосов
/ 15 марта 2020

Я только начинаю работать с ASP. Net Core MVC. У меня есть трудности в создании всплывающего модального. Я пытался создать простую страницу.

Ниже моя модель:

namespace CoreModal.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }

    }
}

Ниже мой EmployeeController:

namespace CoreModal.Controllers
{
    public class EmployeeController : Controller
    {
        public static List<Employee> empList = new List<Employee>() {
            new Employee {Id=1, Name="John", Email="john@gmail.com", Address="Campbell", Phone="1234"}
        };

        public IActionResult Index()
        {
            ViewBag.Employee = empList;
            return View();
        }

        [HttpPost]
        [Route("create")]
        public IActionResult Create(string name, string email, string address, string phone)
        {
            var newEmployee = new Employee
            {
                Name = name,
                Email = email,
                Address = address,
                Phone = phone
            };

            empList.Add(newEmployee);
            ViewBag.Employee = empList;
            return RedirectToAction("Index");
        }
    }
}

В моем индексном представлении я создаю кнопку для запуска всплывающего модального окна для создания новый объект Employee следующим образом:

<a href="#addEmployeeModal" class="btn btn-success" data-toggle="model"><i class="material-icons">&#xE147;</i><span>Add New Employee</span></a>






<d id="addEmployeeModal" class="modal fade" name="addEmployeeModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post" asp-controller="employee" asp-action="create">
                    <div class="modal-header">
                        <h4 class="modal-title">Add Employee</h4>
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label>Name</label>
                            <input type="text" class="form-control" required="required" name="name"/>
                        </div>
                        <div class="form-group">
                            <label>Email</label>
                            <input type="text" class="form-control" required="required" name="email"/>
                        </div>
                        <div class="form-group">
                            <label>Address</label>
                            <input type="text" class="form-control" required="required" name="address"/>
                        </div>
                        <div class="form-group">
                            <label>Phone</label>
                            <input type="text" class="form-control" required="required" name="phone"/>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" />
                        <input type="Submit" class="btn btn-success" value="Add" />
                    </div>
                </form>
            </div>
        </div>
    </d>

Но вместо направления на модальное всплывающее окно он направляет его на URL https://localhost: 44330 / # addEmployeeModal .

Что я сделал не так?

Спасибо

1 Ответ

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

Прежде всего, вы не должны хранить свои данные внутри контроллера, потому что контроллер запускается заново каждый раз, когда он вызывается, и ваши данные будут потеряны. Используйте базу данных для достижения наилучших результатов.

Ваш синтаксис для вызова модального режима немного неправильный. Проверьте здесь для правильного синтаксиса. Это не href (это ваша ошибка!) В основном вы можете скопировать этот код и заменить внутренние части тем, что у вас есть.

https://getbootstrap.com/docs/4.0/components/modal/

* Примечание: вы необходимо использовать bootstrap, чтобы это работало

Удачи!

Редактировать: Вы можете попробовать это: (может потребоваться некоторая настройка)

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
      Add Employee
 </button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
   <div class="modal-dialog" role="document">
    <div class="modal-content">
     <form method="post" asp-controller="employee" asp-action="create">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Add Employee</h5>
         <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
          <div class="form-group">
                        <label>Name</label>
                        <input type="text" class="form-control" required="required" name="name"/>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" class="form-control" required="required" name="email"/>
                    </div>
                    <div class="form-group">
                        <label>Address</label>
                        <input type="text" class="form-control" required="required" name="address"/>
                    </div>
                    <div class="form-group">
                        <label>Phone</label>
                        <input type="text" class="form-control" required="required" name="phone"/>
                    </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <input type="submit" class="btn btn-primary">Add Employee</button>
      </div>
     </form>
    </div>
  </div>
</div>

Кроме того, это Лучше всего отправлять модель в контроллер. Используйте модель в верхней части окна, свяжите ее с моделью сотрудника и отправьте ее в контроллер.

...