I'm trying to get data from a form when submitted and save it into SQL database, but I have a problem with the select tag when submit clicked it returns a null value to [HttpPost] action.
I tried every solution on the web but got no answer...
Please help me...
My code is:
DbContext
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employee { get; set; }
public DbSet<Coding> Coding { get; set; }
}
Employee model:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string NationalCode { get; set; }
public Coding City { get; set; }
}
Coding model:
public class Coding
{
public int Id { get; set; }
public string City { get; set; }
}
Home controller:
[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 view:
@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>
Please help
Would you please give me an example of a ViewModel with my defined classes?
