我试图在提交时从表单获取数据并将其保存到SQL数据库中,但是在提交单击时,select标记存在问题,它返回一个空值作为[HttpPost]
操作。
我尝试了网络上的所有解决方案,但没有得到答案...
请帮我...
我的代码是:
DbContext
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的例子吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句