Search code examples
c#asp.net-web-apimodel-view-controllercascadingdropdown

C# Mvc Web Api Cascading List


This is my controller.

    public class DokuzasController : Controller
{
    public ActionResult AddOrEdit()
    {

        DersViewModel model = new DersViewModel();
        schoolEntities sc = new schoolEntities();
        List<ders> dersList = sc.ders.OrderBy(f => f.Ders1).ToList();

        model.DersList = (from s in dersList
                          select new SelectListItem
                          {
                              Text = s.Ders1,
                              Value = s.DersID.ToString()
                          }).ToList();

        model.DersList.Insert(0, new SelectListItem { Value = "", Text = "Select"});

        return View(model);
    }

    [HttpPost]
    public ActionResult AddOrEdit(DersViewModel model)
    {
        if (model.LectureId == 0)
        {
            HttpResponseMessage response = GlobalVariables.LecturesClient.PostAsJsonAsync("dokuzas", model).Result;
            TempData["SuccessMessage"] = "Saved.";
        }
        else
        {
            HttpResponseMessage response = GlobalVariables.LecturesClient.PutAsJsonAsync("dokuzas/" + model.LectureId, model).Result;
            TempData["SuccessMessage"] = "Successful.";
        }
        return RedirectToAction("Index");
    }

    [HttpPost]
    public JsonResult SaatList(int id)
    {
        schoolEntities sc = new schoolEntities();
        List<saat> saatList = sc.saat.Where(f => f.DersID == id).OrderBy(f => f.Saat1).ToList();
        List<SelectListItem> itemList = (from i in saatList
                                         select
                     new SelectListItem
                     {
                         Value = i.SaatID.ToString(),
                         Text = i.Saat1
                     }).ToList();

        return Json(itemList, JsonRequestBehavior.AllowGet);
    }
}

And this is my AddOrEdit file.

@model Mvc.Models.DersViewModel
@{
ViewBag.Title = "AddOrEdit";
}

@using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
{
@Html.DropDownListFor(m => m.DersID, Model.DersList)
<br /><br />
@Html.DropDownListFor(m => m.SaatID, Model.SaatList)

<br />
<input type="submit" value="Kaydet" class="btn button" />
}

@section scripts{
<script type="text/javascript">
    $(document).ready(function () {
        $("#DersID").change(function () {
            var id = $(this).val();
            var saatList = $("#SaatID");
            saatList.empty();
            $.ajax({
                url: '/Dokuzas/SaatList',
                type: 'POST',
                dataType: 'json',
                data: { 'id': id },
                success: function (data) {
                    $.each(data, function (index, option) {
                        saatList.append('<option value=' + option.Value + '>' 
+ option.Text + '</option>')
                    });
                }
            });
        });
    });
</script>
}

I have a table and this table contains Dersadi and Dagilimi properties. I wanted to create a cascading list and add to table from this list from DersList to Dersadi and from SaatList to Dagilimi. But i choose items and select submit button i can submit it but it added null to the table. It did not add what i choose from the list. How can i fix this?


Solution

  • in the view, you can use the DropDownList helper method to render the SELECT element with the data we set to the Model.DersList. We will also add our second dropdown as well.

        @using (Html.BeginForm("AddOrEdit", "Dokuzas", FormMethod.Post))
        {
        @Html.DropDownList("DersID", Model.DersList as SelectList)
        <select name="id" id="SaatID" data-url="@Url.Action("SaatList","Home")">
    
        <br />
        <input type="submit" value="Kaydet" class="btn button" />
        }
    
    <script type="text/javascript">
        $(function(){
        $("#DersID").change(function (e) {
            var $SaatID = $("#SaatID");
            var url = $SaatID.data("url")+'?id='+$(this).val();
            $.getJSON(url, function (items) {
                $.each(items, function (a, b) {
                    $vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
                });
            });
        });    
    });
    
    </script>