Home > database >  asp.net core - form values return null
asp.net core - form values return null

Time:02-05

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  asp-action="CreateEmployee" asp-controller="Employees" method="post">
        <div >
            <div >
                <div >
                    <label for="Name" >İsim</label>
                    <input asp-for="e.Name" type="text"  id="Name">
                    <div >
                        İ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");
        }

CodePudding user response:

Set the name attribute in the input tag:

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

The second solution is to use model name item3 generated by the MVC:

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

CodePudding user response:

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)
{
    var context = new HR_ManagementContext();
    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
  • Related