Я пытаюсь создать окно автозаполнения для CategoryName, и оно не работает. После поиска по многим темам здесь я решил создать свою собственную.
Моя команда контроллера:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SDMan.Context;
using SDMan.Models;
using SDMan.Services.Interfaces;
namespace SDMan.Controllers
{
public class IncidentController : Controller
{
//private readonly SignInManager<UserModel> signInManager;
private readonly IIncidentService _modelService;
private readonly IPriorityService _priorityService;
private readonly ICategoryService _categoryService;
private readonly IDepartmentService _departmentService;
private readonly SDManDbContext _context;
public IncidentController(IIncidentService modelService, IDepartmentService departmentService, ICategoryService categoryService, IPriorityService priorityService, SDManDbContext context)
{
_priorityService = priorityService;
_categoryService = categoryService;
_departmentService = departmentService;
_modelService = modelService;
_context = context;
}
public IActionResult Index()
{ //Po utworzeniu userów
//var user = User.Identity.Name;
//var modelData = _modelService.GetAll().Where(x => x.UserId == user);
//Przed utworzeniem userow
var modelData = _modelService.GetAll();
return View(modelData);
}
public IActionResult Create()
{
IncidentModel model = new IncidentModel();
//model.ListPriorites = new SelectList(_modelService.GetAll(), model.Priority);
//model.ListPriorites = new SelectList(_modelService.GetAll().ToList());
model.ListPriorities = new SelectList(_priorityService.GetAll().Select(x => x.Name).ToList(), model.PriorityName);
model.ListDepartments = new SelectList(_departmentService.GetAll().Select(x => x.Name).ToList(), model.DepartmentName);
model.ListCategories = new SelectList(_categoryService.GetAll().Select(x => x.Name).ToList(), model.CategoryName);
//model.ListPriorities = _priorityService.GetAll().ToList();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create([FromForm]IncidentModel model) //[FromForm] - potrzebne do mapowania danych z formularza na obiekt w przypadku gdy korzystamy z Razora lub zwykłego HTMLa. Przy taghelperach nie jest to konieczne tak jak w tym przypadku
{
if (ModelState.IsValid)
{
try
{
//var user = await signInManager.UserManager.FindByIdAsync(User.Identity.ToString());
//model.CreatedBy = model.ModifiedBy = user;
//model.UserId = User.Identity.Name;
// model.ListPriorites = new SelectList(_modelService.GetAll());
_modelService.Create(model);
//context.SaveChanges();
}
catch (Exception)
{
return View(model);
}
return Redirect("Index");
}
else
{
return View(model);
}
}
public IActionResult Remove(int id)
{
return View(_modelService.Get(id));
}
[HttpPost]
public IActionResult RemoveConfirm(int id)
{
try
{
_modelService.Delete(id);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.InnerException);
throw;
}
return Redirect("Index");
}
public IActionResult Edit(IncidentModel model,int id)
{
//model.ListPriorities = new SelectList(_priorityService.GetAll().Select(x => x.Name).ToList(), model.PriorityName);
//model.ListDepartments = new SelectList(_departmentService.GetAll().Select(x => x.Name).ToList(), model.DepartmentName);
//model.ListCategories = new SelectList(_categoryService.GetAll().Select(x => x.Name).ToList(), model.CategoryName);
return View(_modelService.Get(id));
}
[HttpPost]
public IActionResult EditSave(IncidentModel model)
{
try
{
_modelService.Update(model);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.InnerException);
throw;
}
return Redirect("Index");
}
public IActionResult Details(int id)
{
//IncidentModel model = new IncidentModel();
//model.ListPriorities = new SelectList(_priorityService.GetAll().Select(x => x.Name).ToList(), model.PriorityName);
//model.ListDepartments = new SelectList(_departmentService.GetAll().Select(x => x.Name).ToList(), model.DepartmentName);
//model.ListCategories = new SelectList(_categoryService.GetAll().Select(x => x.Name).ToList(), model.CategoryName);
return View(_modelService.Get(id));
}
public IActionResult Show()
{
var modelData = _modelService.GetAll();
return View(modelData.Count());
}
[HttpPost]
public JsonResult CreateJS(string prefix)
{
var List = _categoryService.GetAll();
var CatList = (from N in List
where N.Name.StartsWith(prefix)
select new { N.Name });
return Json(CatList);
}
}
}
Просмотр со сценарием:
@model SDMan.Models.IncidentModel
<h4>RecipeModel</h4>
<hr />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#CategoryName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Incident/CreateJS",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CategoryName, value: item.CategoryName};
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<div class="col-md-16">
<form asp-action="Create">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<div class="col-md-12">
@Html.EditorFor(model => model.CategoryName, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
</div>
}
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="IncidentDescription" class="control-label"></label>
<input asp-for="IncidentDescription" class="form-control" />
<span asp-validation-for="IncidentDescription" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
@*<div class="col-sm-3">
<select asp-for="PriorityName" asp-items="Model.ListPriorities"></select>
</div>
<div class="col-sm-3">
<select asp-for="CategoryName" asp-items="Model.ListCategories"></select>
</div>
<div class="col-sm-3">
<select asp-for="DepartmentName" asp-items="Model.ListDepartments"></select>
</div>*@
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
Изображение выпуска:
В моей БД у меня в данный момент есть таблица категорий, как 4 категории, но когда я что-то печатаю, всплывающего окна нет. Когда я ставлю точки останова на моем JsonResult Create JS и go в Создание инцидента, ничего не происходит, как действие никогда не запускалось.