[Solved] ASP NET Core (MVC) problem with passing parameters from the view to the controller


Because the parameter names you accept are answer1, answer2, you should have a matching name in your view to make it possible to bind successfully.

You can modify your front-end code as follows(DropDownListForto DropDownList):

@model CommonEntity
@using (Html.BeginForm("Find", "Hello"))
{
@Html.DropDownList("answer1", new SelectList(ViewBag.Location, "Title", "Title"))
@Html.DropDownList("answer2", new SelectList(ViewBag.JobTitle, "Title", "Title"))
<button type="submit">Find</button>
}

Your Controller:

public class HelloController : Controller
{
    [HttpGet]
    public IActionResult Index()
    {

        var locations = new List<Location>()
    {
           new Location()
           {
                Id = 0,
            Title = "Russia"

        },
            new Location()
           {
                Id = 1,
            Title = "Canada"
           }
    };

        ViewBag.Location = locations;

        var jobs = new List<JobTitle>()
    {
        new JobTitle()
        {
            Id = 0,
            Title = "Manager"
        } ,
        new JobTitle()
        {
            Id = 1,
            Title = "Programmer"
        }
    };

        ViewBag.JobTitle = jobs;


        return View();
    }

    [HttpPost]
    public string Find(string answer1,string answer2)
    {
        return "Fine";
    }
}

Class:

 public class CommonEntity
{
    public Location Location { get; set; }
    public JobTitle JobTitle { get; set; }

}
public class JobTitle
{
    public long Id { get; set; }
    public string Title { get; set; }
}
public class Location
{
    public long Id { get; set; }
    public string Title { get; set; }
}

Result:
enter image description here
enter image description here

0

solved ASP NET Core (MVC) problem with passing parameters from the view to the controller