Mahajan344
Mahajan344

Reputation: 2550

Get dropdown value and text in controller mvc4 razor

I am working on MVC4 project. I have form where dropdownlist is populated with text and value field.

@Html.DropDownList("SourceDropDownList", new SelectList(""), "-Select-", new { @class = "validate[required]" })

This dropdown is populated from other dropdown change event here is that code

function OnSourceFacilityDropDownChange(source, e) {
        $("#SourceDropDownList").empty();
        var curOpt = new Option('-Select-', "");
        $("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;

        if (source.value != '') {
            var url = getUrl() + '/AdminPanel/GetIns/?id=' + Math.random();
            $.ajax({
                url: url,
                data: { clientid: $("#SourceDropDown").val(), strFacility: source.value }, //parameters go here in object literal form
                type: 'GET',
                datatype: 'json',
                success: function (data) {
                    $.each(data, function (index, item) {
                        var curOpt = new Option(item.T, item.T);
                        curOpt.setAttribute("title", item.T);
                        $("#SourceDropDownList").get(0).options[$("#SourceDropDownList").get(0).options.length] = curOpt;
                    });
                },
                error: function (request, status, error) { alert("Status: " + status + "\n Exception Handling :  \n" + request.responseText); },
                complete: function () {
                    $("#divLoading").hide();
                }
            });
        }
        else {
        }
    }

and code in AdminPanel/GetIns controller is

    public JsonResult GetInspection(int clientid, string strFacility)
            {

var objlist = (from d in Context.tbl_insp
                               orderby d.str_insp ascending
                               where d.clientid.Equals(ClientId))
                               select new { T= d.str_inspname, V= d.dte_start.Value.ToShortDateString()}).ToArray();                

                Array InspectionList = objlist;
                return Json(InspectionList, JsonRequestBehavior.AllowGet);
            }

And in model class i have initialized the property of dropdown

public string SourceDropDownList{ get; set; }

now i am getting only text values of what i select in SourceDropDownList dropdown..

How do i get the value also ??

Upvotes: 0

Views: 5065

Answers (1)

Jaimin
Jaimin

Reputation: 8020

Try with this,Just Example

View

  @Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
    @Html.DropDownList("CustomerNameId", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "-- Select --")

Script

<script type="text/javascript">
    $(document).ready(function () {
  $("#CustomerId").change(function () {

            var Id = $("#CustomerId").val();

            $.ajax({
                url: '@Url.Action("GetCustomerNameWithId", "Test")',
                type: "Post",
                data: { CustomerNameId: Id },
                success: function (listItems) {



                    var STSelectBox = jQuery('#CustomerNameId');
                    STSelectBox.empty();
                    if (listItems.length > 0) {
                        for (var i = 0; i < listItems.length; i++) {
                            if (i == 0) {
                                STSelectBox.append('<option value="' + i + '">--Select--</option>');
                            }
                            STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');

                        }

                    }
                    else {
                        for (var i = 0; i < listItems.length; i++) {
                            STSelectBox.append('<option value="' + listItems[i].Value + '">' + listItems[i].Text + '</option>');

                        }
                    }
                }


            });

        });
});
</script>

Controller

 public JsonResult GetCustomerNameWithId(string CustomerNameId)
        {
            int _CustomerNameId = 0;
            int.TryParse(CustomerNameId, out _CustomerNameId);
            var listItems = GetCustomerNameId(_CustomerNameId).Select(s => new SelectListItem { Value = s.CID.ToString(), Text = s.CustomerName }).ToList<SelectListItem>();
            return Json(listItems, JsonRequestBehavior.AllowGet);
        }

Model

public class CustomerModel
{
    public int CustomerId { get; set; }

        public int CustomerNameId { get; set; }
}

Upvotes: 1

Related Questions