-1

I am new to MVC.NET 5; I am developing an application with dropdowns and forms. My dropdowns are created my model and I cant fugure out how to take the falues from the dropdowns. Here is part of the code:

first dropdown partial view:

@using System.Data.SqlClient
@model Cars.Web.Models.TestModel

@using (Ajax.BeginForm("GetByMake", "Cars", null, new AjaxOptions
{
    HttpMethod = "POST",
    UpdateTargetId = "models",
    InsertionMode = InsertionMode.Replace
}, new { id = "selectMarke" }))
{
    @Html.DropDownListFor(
        m => m.SelectedMarkeId,
        new SelectList(Model.Markes, "Id", "Name"),
        String.Empty
        )
}

<script>
    $('#SelectedMarkeId').change(function () {
        console.log("asd");
        $('#selectMarke').submit();
    });
</script>

here is the second:

@model  Cars.Web.Models.TestModel

@if (Model.Models != null && Model.Models.Any())
{
      @Html.DropDownList(
            "models",
            new SelectList(Model.Models, "Id", "ModelName"),
            string.Empty
            )
}

I can pass from the firstone the id to the second one form the controller, but I think, that is not the right way. I wonder if I add more forms, how to bind them with this two drop down on submit. Thanks

  • this might be helpful http://stackoverflow.com/questions/22952196/cascading-dropdown-lists-in-asp-net-mvc-5/30945495#30945495 – Alex Art. Sep 25 '15 at 18:00

1 Answers1

1

When you use:

@Html.DropDownListFor(
        m => m.SelectedMarkeId,
        new SelectList(Model.Markes, "Id", "Name"),
        String.Empty
        )

The name of the dropdownlist will be "SelectedMarkeId".

When you use:

@Html.DropDownList(
            "models",
            new SelectList(Model.Models, "Id", "ModelName"),
            string.Empty
            )

The name of the dropdownlist will be "models"

The controller must have a parameters that match with the name of the inputs. Like this:

[HttpPost]
public ActionResult SomeAction (int models, int SelectedMarkeId)
{
    //SelectedMarkeId is the selected value of the first drop down list
    //models is the selected value of the second drop down list
    //your code here
}

You can also use an object, that contains properties that match with the names of the inputs. Like This:

public class TestModel
{
     public int models { get; set; }
     public int SelectedMarkeId { get; set; }
}

[HttpPost]
public ActionResult SomeAction (TestModel model)
{
    //SelectedMarkeId is the selected value of the first drop down list
    //models is the selected value of the second drop down list
    //your code here
}
Fabio
  • 11,892
  • 1
  • 25
  • 41