Link to home
Start Free TrialLog in
Avatar of Mohammad Alsolaiman
Mohammad AlsolaimanFlag for Saudi Arabia

asked on

Using dropdown list control to pass text value to javascript parameter.


Server-side processing datatable.

I have three filters

  • CustomerName
  • ProductName
  • SalesPersonName

It works very good with the type of all of these three controls are input textbox.

I need to have ProductName as a dropdown list.

I had use these two types of cntrols:

  • @Html.DropDownList("ProductName", (IEnumerable<SelectListItem>)ViewData["ProductList"], "select product", new { @id = "ProductID", @class = "form-control" })
  • @Html.DropDownListFor(model => model.ProductId,ViewBag.ProductList as SelectList,"-- Slect Product Name --" ,new { @class = "form-control" })

But I had struggle in passing the text value to the parameter.

I need your help, please.

@model EFMVCbasicApp.Models.GetProductClass
@{     ViewBag.Title = "IndexSales"; } <!--Page header--> <section class="single-page-header">     <div class="container">         <div class="row">             <div class="col-md-12">                 <h2>All Sales Data</h2>                 <ol class="breadcrumb header-bradcrumb">                     <li><a href="/">Home</a></li>                     <li class="active">Sales Data</li>                 </ol>             </div>         </div>     </div> </section> <!--End Page header--> <!--Start DataTable Ajax Pagination--> <div class="container-fluid">     <!--Start Filter Input control search -->     <div id="sales_filter" class="row mt-30">         <div class="form-group  col-md-4">             <input id="CustomerName" name="CustomerName" placeholder="Customer Name..." class="form-control" />         </div>         <div class="form-group col-md-4">             <input id="ProductName" name="ProductName" placeholder="Product Name..." class="form-control" />             @*@Html.DropDownList("ProductName", (IEnumerable<SelectListItem>)ViewData["ProductList"], "select product", new { @id = "ProductID", @class = "form-control" })*@             @*@Html.DropDownListFor(model => model.ProductId,ViewBag.ProductList as SelectList,"-- Slect Product Name --" ,new { @class = "form-control" })*@         </div>         <div class="form-group col-md-4">             <input id="SalesPersonName" name="SalesPersonName" placeholder="Sales Person Name..." class="form-control" />         </div>     </div>     <div class="row">         <div class="col-md-12">             <a class="btn btn-primary float-right" id="btnApplyFilter">Apply Filter</a>         </div>     </div>     <!--End Filter Input control search -->     <!--DataTable-->     <div class="mt-20">         <table id="dtSales" class="table table-bordered">             <!--Header columns of the table-->             <thead>                 <tr>                     <th>CustomerID</th>                     <th>CustomerFullName</th>                     <th>ProductID</th>                     <th>ProductName</th>                     <th>ProductPrice</th>                     <th>Quantity</th>                     <th>SalesID</th>                     <th>SalesPersonFullName</th>                     <th>SalesPersonID</th>                     <th>TotalPrice</th>                 </tr>             </thead>         </table>     </div>     <!--Pagination-->     <div class="mt-20">         <div id="pagination"></div>     </div> </div> <!---End DataTable Ajax Pagination--> @section Scripts{     <script>         //defualt settings         var totalRecords = 100;         var pageSize = 10;         var currentPage = 1;         // Load Data on page load         $(document).ready(function () {             DisplayDataTable();         });         // Apply  search filters         $("#btnApplyFilter").click(function () {             DisplayDataTable();         });         // Display DataTable         function DisplayDataTable() {             // initialize show pagination             showPagination(totalRecords, pageSize);             // initialize dataTable and fetch table data             LoadDataTable();             // fetch total number of records ajax call             $.ajax({                  type: "POST",                  url: "@Url.Action("GetTotalCount", "Employee")",                  data: {                     CustomerName:$("#CustomerName").val(),                    ProductName :$("#ProductName").val(),                      SalesPersonName: $("#SalesPersonName").val()                  },                 success: function (result) {                     totalRecords = result["totalRows"];                     showPagination(totalRecords, pageSize);                 },                 error: function (error) {                     alert("error: " + error);                 }              });         }         // DataTable Plugin Setup         function LoadDataTable() {             $('#dtSales').dataTable().fnClearTable();             $('#dtSales').dataTable().fnDestroy();                 $('#dtSales').DataTable({                     "serverSide": true,                     "paging": false,                     "searching":false,                    "ajax": {                     "ContentType":"application/json; charset=utf-8",                     "url": "@Url.Action("GetSalesData", "Employee")",                     "type": "POST",                        data: function (dtparams) {                            if ($("#pagination").pagination('getCurrentPage')) {                                currentPage = $("#pagination").pagination('getCurrentPage');                            }                         dtparams.PageNumber = currentPage                         dtparams.PageSize = pageSize;                         dtparams.CustomerName = $("#CustomerName").val();                         dtparams.ProductName = $("#ProductName").val();                         dtparams.SalesPersonName = $("#SalesPersonName").val();                         return dtparams;                     },               },                 "processing": true,                 "columns": [                     {                         "data": "CustomerID",                     },                     {                         "data": "CustomerFullName",                     },                     {                         "data": "ProductID",                     },                     {                         "data": "productName",                     },                     {                         "data": "productPrice",                     },                     {                         "data": "Quantity",                     },                     {                         "data": "SalesID",                     },                     {                         "data": "SalesPersonFullName",                     },                     {                         "data": "SalesPersonID",                     },                     {                         "data": "totalprice",                     }                 ],                 });         }         // Pagination Plugin Setup         function showPagination(totalRecords,pageSize) {           $("#pagination").pagination({                 items: totalRecords,  /* set total number of records*/                 itemsOnPage: pageSize, /* set page size here */                 cssStyle: 'light-theme', /* use css theme in file "simplePagination.css": light theme,dark-theme,compact-theme */                 /*On Page Click Update data Of Page */                 onPageClick: function () {                     LoadDataTable();                 }             });         }     </script> } <!--  How come JS parameters passed from MVC view to controller?  ActionResult is an inheritable Type which has many Types that derive from it. I wouldn't focus too much on that one other than to know what it is. The answer to your original question -- if I'm understanding it correctly -- is: - The jQuery request has a dynamically built data value. - When the POST request is initialized (at run time) it executes the function that is its data value -- the one that returns dtParams. - dtParams is then submitted to the GetSalesData MVC endpoint/function, and the ASPNET ModelBinder automagically handles deserializing the json data into the SalesRequestModel. The easiest way to think of it is that because you're pointing the request at GetSalesData and because your POST body has the same shape as the SalesRequestModel then the ModelBinder knows exactly what to do with it. So yes, your assertion is correct. -->

Open in new window

Avatar of leakim971
Flag of Guadeloupe image

what parameter ? could you point a line in your JS code ?
With jQuery, to get text value of a dropdown, it's easy :


Open in new window

Instead of pasting here an entire chunk of code that will waste our time to read, please revise your question and show only relevant code (and filter redundant information, minimize only to what's required to understand the symptom). The only snippets of code you should paste are the DropDownList declaration (if needed, a bit code around it) and the Javascript function code that is expecting the value from the DropDownList control separated (not together in a single code block).

Reply back here when you've modified the code and I'll come back to review your question again.
Avatar of Mohammad Alsolaiman


I mean by passing dropdownlist (text) when selected, to parameter is:
// fetch total number of records ajax call
                 type: "POST",
                 url: "@Url.Action("GetTotalCount", "Employee")",
                 data: {
                   ProductName :$("#ProductName").val(),
                     SalesPersonName: $("#SalesPersonName").val()

Open in new window

dtparams.ProductName = $("#ProductName").val();

Open in new window

Avatar of leakim971
Flag of Guadeloupe image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial