Share via


How to pass data from View to Controller without submitting the form

Question

Saturday, August 5, 2017 9:33 PM

I have a DropDownList in my View and I have captured the ID of the selected value in DropDownList and pass that value as an argument in one of my Controller action method. I have used DropDownList change function in JavaScript to capture the value but I want to pass this in my controller.

@Html.DropDownList("ddlL", new SelectList(string.Empty, "Value", "Text"), "Select")
<script type="text/javascript">
$("#ddlL").empty();
  $.ajax({
            type: 'POST',
            url: '@Url.Action("LoadLDet")',
            datatype: 'JSON',
            success: function (data) {
            $("#ddlL").append('<option value=' + '0' + '>' + 'Select' + '</option>');
            $.each(data, function (key, value) {

            $("#ddlL").append('<option value=' + value.LId + '>' + value.LName + '</option>');
        });
      },
      error: function (ex) {
        alert('Failed to display Data');
      }
});
$("#ddlL").change(function () {
  var LID=$(this).val();
  alert(LID);
});
</script>

Here With the help of LoadLDet() I am getting all the data and binding it in DropDownList

[HttpPost]
    public JsonResult LoadLDet()
    {
        MyService.ServiceInfoClient Service = new MyService.ServiceInfoClient();
        var Loc = Service.GetLocList();
        return Json(Loc);
    }

I have another ActionResult ExportDataInExcel() class in which I want to pass selected DropDownList items LId and WId as argument in one of the method which I am calling to get data which needs to be exported. Please guide me how I can pass "LId" from view to controller which I am capturing in the Ajax.

public ActionResult ExportDataInExcel()
        {
            ExportData(LId, WId, xyz);
            return View("Index");
        }

 

All replies (1)

Monday, August 7, 2017 5:18 AM âś…Answered

Hi Ashish Kumar,

Do you mean that you want to pass the value of dropdown(LId) to ExportDataInExcel controller by using ajax? I've modified your code, please take it as a reference.

$("#ddlL").change(function () {
  var LID=$(this).val();
    alert(LID);
    $.ajax({
        type: 'POST',
        url: '@Url.Action("ExportDataInExcel")',
        datatype: 'JSON',
        data: { LId: LID },
        success: function () {
            alert("success!");
        },
        error: function () {
            alert("error!");
        }
    })
});

Controller:

        public ActionResult ExportDataInExcel(int LId)
        {
            return View("Index");
        }

Best Regards,

Jean