Search code examples
asp.netformsasp.net-core

asp.net core - form values return null


Passing department and title models for use data in selectbox and passing employee model for save data from user. tring to pass values from partial view but in controller values return null.

partial view:

@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>

controller:

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");
        }

Solution

  • Thx @Jackdaw his answer also working too.

    I found an alternative

    in Controller you can bind model:

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

    Item3 is the prefix of tuple model.

    @model (List<Department> Departments, List<Title> Titles, Employee e)
    
    • Department = Item1
    • Titles = Item2
    • Employee = Item3