Search code examples
c#asp.net-mvchtml.dropdownlistfor

Asp.Net MVC Get value from Dropdownlist to PartialView


In my main page I have Dropdownlist of Cars. And it works fine.
And When I select one car from Dropdownlist I want to get back all car modells who belongs to the selected Car from Dropdownlist in the same view, let say under Dropdownlist. DropDownlist with Cars and Models of the selected cars in the same View (in Main view). I tried with PartialView but I'am not so good when it comes PartielView and html code This is my action to get CarModels, and I think this must be as PartialView

[HttpGet]
public ActionResult GetCarModel(int? carId)
{
    List<CarModelVW> listOfCarModel;

    using (Db db = new Db())
    {
        listOfCarModel = db.CarModel.ToArray()
                        .Where(x => carId == null || carId == 0 || x.carId == carId)
                        .Select(x => new CarModelVW(x))
                        .ToList();

    }
    return View(listOfCarModel);
}

In my Main View with DropDownlist

<div class="form-group">
    <label class="control-label col-md-2" for="HasSidebar"> Car </label>
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.CarId, Model.Cars, "---Select car---", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CarId, "", new { @class = "text-danger" })
    </div>
</div>

And here below Dropdownlist I want to get all carmodels of selected car But I think I have to create <div> </div> with Id or span .. but I'am not sure how to do here.

And here is javascript I'am trying to use

$("#CarId").change(function () {        
    var carId = $(this).val();
    if (carId) {
        window.location = "/an/GetCarModel?carId=" + carId;
    }
    return false; 
});

How do I get this action GetCarModel below Dropdownlist view? Thank you in advance.


Solution

  • Just like Roman said, instead of navigating to the url, you should send an ajax call to the control.

    First of all, add an id to your dropdownlist.

    Secondly, in the Onchange function add an ajax call to get cars:

    var dropdownval = $("#//Id of dropdown").val();
    var json = '{Id: ' + dropdownval + '}';
    
    $.ajax({
        url:'@Url.Action("GetCarModel", "//The controller")',
        type:'POST',
        data: json,
        contentType:'Application/json',
        success:function(result){
            //Do whatever
        }
    })
    

    You can then do whatever with the result you pass back to the ajax call