Я пытаюсь получить данные из формы при отправке и сохранить их в базе данных SQL, но у меня проблема с тегом select, когда при нажатии кнопки отправки он возвращает нулевое значение для действия [HttpPost]
.
Я пробовал все решения в Интернете, но не получил ответа...
Пожалуйста, помогите мне...
Мой код:
Дбконтекст
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employee { get; set; }
public DbSet<Coding> Coding { get; set; }
}
Модель сотрудника:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string NationalCode { get; set; }
public Coding City { get; set; }
}
Модель кодирования:
public class Coding
{
public int Id { get; set; }
public string City { get; set; }
}
Домашний контроллер:
[HttpGet]
public IActionResult Create()
{
var cityList = _dbContext.Coding.ToList();
ViewBag.city = cityList;
return View();
}
[HttpPost]
public IActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
_employeeRepository.AddEmployee(employee);
return View();
}
return View();
}
Представление Create.cshtml:
@model Emp.Models.Employee
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form asp-controller = "Home" asp-action = "Create" method = "post">
<table>
<tr>
<td>
<label asp-for = "Name"></label>
</td>
<td>
<input asp-for = "Name" />
</td>
</tr>
<tr>
<td>
<label asp-for = "NationalCode"></label>
</td>
<td>
<input asp-for = "NationalCode" />
</td>
</tr>
<tr>
<td>
<label asp-for = "City"></label>
</td>
<td>
<select asp-for = "City"
asp-items=@(new SelectList(ViewBag.city , "Id", "City"))
class = "custom-select">
</select>
</td>
</tr>
</table>
<button type = "submit">submit</button>
</form>
</body>
</html>
Пожалуйста помоги
Не могли бы вы привести пример ViewModel с моими определенными классами?
Вы должны использовать ViewModel или добавить новое свойство, которое может быть CityId
вместо использования класса Coding
для City
Используйте asp-for = "City.Id"
в теге выбора:
<select asp-for = "City.Id"
asp-items=@(new SelectList(ViewBag.city , "Id", "City"))
class = "custom-select">
</select>
Не могли бы вы привести пример модели представления, содержащей мои классы?