skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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

  2. Set the name attribute in the input tag:

    <input asp-for="e.Name" type="text" class="form-control" 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");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search