asp.net 核心-表单值返回空值

6jygbczu  于 2023-02-06  发布在  .NET
关注(0)|答案(2)|浏览(169)

为selectbox中的使用数据传递部门和职务模型,并为用户的保存数据传递雇员模型。特灵从部分视图传递值,但在控制器中,值返回null。
局部视图:

@model (List<Department> Departments, List<Title> Titles, Employee e)

    <form class="g-3" asp-action="CreateEmployee" asp-controller="Employees" method="post">
        <div class="row">
            <div class="col-lg-6">
                <div class="mb-3">
                    <label for="Name" class="form-label">İsim</label>
                    <input asp-for="e.Name" type="text" class="form-control" id="Name">
                    <div class="invalid-feedback">
                        İsim alanı boş bırakılamaz.
                    </div>
                </div>
            </div>
        </div>
        <button type="submit">Tek Form</button>
    </form>

控制器:

public IActionResult CreateEmployee()
        {
            HR_ManagementContext context = new HR_ManagementContext();
            var departments = context.Departments.ToList();
            var titles = context.Titles.ToList();

            var models = (departments, titles, new Employee());

            return View(models);
        }
 [HttpPost]
        public IActionResult CreateEmployee(Employee employee)
        {

            return RedirectToAction("CreateEmployee");
        }
deikduxw

deikduxw1#

设置input标记中的name属性:

<input asp-for="e.Name" type="text" class="form-control" id="Name", name="employee.Name">

第二种解决方案是使用MVC生成的模型名称item3

[HttpPost]
public IActionResult CreateEmployee(Employee item3)
{
    return RedirectToAction("CreateEmployee");
}
7rfyedvj

7rfyedvj2#

感谢寒鸦他的回答也起作用了。
我找到了另一种选择
在控制器中,您可以绑定模型:

public IActionResult CreateEmployee([Bind(Prefix = "Item3")]Employee employee)
{
    var context = new HR_ManagementContext();
    return RedirectToAction("CreateEmployee");
}

Item3是元组模型的前缀。

@model (List<Department> Departments, List<Title> Titles, Employee e)
  • 部门=项目1
  • 标题=项目2
  • 员工=项目3

相关问题