Thursday, 6 March 2014

Populate drop down via AJAX using MVC4 C# when page loads.

1. Create a view that contains one drop down list for displaying items into it.

2. In Controller write a method that return JsonResult. And don't forget to mention it as [HttpPost]     since we will be using AJAX POST method, Ajax data type as Json hence the return type of             method is JsonResult.

3. We will create a function loadChannels() that will be called when the document is ready. This is        achieved using Jquery as :- 
               //Function call goes here.

4. The method that we have written in controller (NOTE STEP 2) which will return JsonResult will     get called via AJAX from the method loadChannels() (NOTE STEP 3).

View as FpcDetails.cshtml

    ViewBag.Title = "FpcDetails";
    Layout = "~/Views/Shared/_LayoutPrivate.cshtml";
@using (Html.BeginForm("FpcDetails", "Fpc", FormMethod.Post, new { enctype = "multipart/form-data", id = "form" }))
                    Select Channel:
                    @Html.DropDownList("channelsList", new List<SelectListItem> { }, string.Empty, new {                                                                   @class = "DropDown", @id = "dropDownChannels" }

    <input type="hidden" id="hdnChannels" />

//Document.ready function calling loadChannels().

<script type="text/javascript">

    $(document).ready(function () {

/* Defining loadChannels() function */

    /*Loading channels on page load*/
  function loadChannels() {
        var options = {};
/* url for ajax to call a method GetChannels in the controller Fpc that will return JsonResult */

        options.url = '@Url.Action("GetChannels", "Fpc")';

/* Method type of Ajax is POST. Same will be mentioned in controller GetChannels() method as [HttpPost] */
        options.type = "POST";

/* Type of Ajax is json. This will  be the return type of method defined in Controller.i.e., JsonResult. */

        options.dataType = "json";
        options.contentType = "application/json";

/* channels passed as argument in the function as used to get the returned values from the controller back to       the view. This will give us an List of Id and Name. Hence we need to iterate over it in order to display           them. */

        options.success = function (channels) {

/* Empty the drop down list before appending any new values. */

            $("#dropDownChannels").append("<option value=></option>");
            for (var i = 0; i < channels.length; i++) {
                $("#dropDownChannels").append("<option value=" + channels[i].Id + ">" + channels[i].Name +                                                                           "</option>");
            $("#dropDownChannels").prop("disabled", false);

/* If there is any problem in Ajax, error method will get invoked. */

        options.error = function () { alert("Error retrieving Channels!"); };



/* Inside our controller we just add the following code. */

/*Get all Channels via AJAX */
        public JsonResult GetChannels()
            List<AMSChannel> channels;
            channels = context.AMSChannels.ToList();
            var result = (from x in channels select new { Id = x.ChannelId, Name = x.ChannelName });
            return Json(result, JsonRequestBehavior.AllowGet);

No comments: