select table row value populate in form control(Dropdown,text field)

Analyst_SQL 3,576 Reputation points
2023-02-25T09:43:11.6066667+00:00

I am selecting or Clicking on row of table, then relevant data from get populate in downdown and text field,

issue is that text field is getting populate ,but dropdown field is not getting populating ,i am sharing my whole code..

View

@model ERP_APP.Models.ItemModel

@{
    ViewBag.Title = "CreaterItem";
   
}


<div class="col-lg-8">
    <div class="card card-default mb-5">
        <div class="card-header">Employee Form</div>
        <div class="card-body">

            @using (Html.BeginForm("CreateItem", "Item", FormMethod.Post))

            {
                @Html.AntiForgeryToken()

            <div class="form-horizontal">

                <hr />
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })


                <div class="form-group">
                    @Html.LabelFor(model => model.Descriptionitem, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Descriptionitem, new { htmlAttributes = new { @class = "form-control", @id = "item_Name" } })
                        @Html.ValidationMessageFor(model => model.Descriptionitem, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.BaleSize, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.BaleSize, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.BaleSize, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.weight, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.weight, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.weight, "", new { @class = "text-danger" })
                    </div>
                </div>





                <div class="form-group">
                    @Html.LabelFor(model => model.SecID, "Select Department Level", htmlAttributes: new { @class = "control-label col-md-6" })
                    <div class="col-md-10">
                       @* @Html.DropDownList("SecId", null, "Select Department", htmlAttributes: new { @class = "form-control", @id = "select2-1" })*@

                        @Html.DropDownList("SecId", (SelectList)ViewBag.secid, "Select", htmlAttributes: new { @class = "form-control", @id = "select2-1" })

                        @Html.ValidationMessageFor(model => model.SecID, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(model => model.IDUOM, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.IDUOM, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.IDUOM, "", new { @class = "text-danger" })
                    </div>
                </div>




                <div class="form-group">
                    @Html.LabelFor(model => model.CID, "Select Category Level", htmlAttributes: new { @class = "control-label col-md-6" })
                    <div class="col-md-10">
                        @Html.DropDownList("cID", null, "Select Department", htmlAttributes: new { @class = "form-control", @id = "select2-2" })
                        @Html.ValidationMessageFor(model => model.CID, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input type="submit" value="Create" class="btn btn-default" />
                    </div>
                </div>
            </div>


            }
            <h4>Item Search</h4>
            <hr />
            <div class="form-group">
                @Html.LabelFor(model => model.CodeItem, "Select Item", htmlAttributes: new { @class = "control-label col-md-6" })
                <div class="col-md-10">
                    @Html.DropDownList("codeitem", null, "Select Item", htmlAttributes: new { @class = "form-control", @id = "select2-3" })
                    @Html.ValidationMessageFor(model => model.CodeItem, "", new { @class = "text-danger" })
                </div>
            </div>



            <section class="content">
                <div class="row">
                    <div class="col-xs-12">
                        <div class="box box-primary">


                            <div class="box-body">
                                <table id="example1" class="table table-bordered table-striped">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Item Name</th>
                                            <th>Section</th>
                                            <th>BaleSize</th>
                                            <th>weight</th>
                                            <th>UOM</th>
                                            <th>Action</th>

                                        </tr>
                                    </thead>
                                    <tbody>

                                        @foreach (var item in Model.Itemss)
                                        {
                                            <tr>
                                                <td>@Html.DisplayFor(module => item.CodeItem)</td>
                                                <td>@Html.DisplayFor(module => item.Descriptionitem)</td>
                                                <td>@Html.DisplayFor(module => item.Section)</td>
                                                <td>@Html.DisplayFor(module => item.BaleSize)</td>
                                                <td>@Html.DisplayFor(module => item.weight)</td>
                                                <td>@Html.DisplayFor(module => item.UOM)</td>
                                                
                                            </tr>
                                        }
                                    </tbody>
                                    <tfoot>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>




            </section>

        </div>
    </div>
</div>

<script src="~/Content/Template/vendor/ddlsearch.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#select2-3").on('change', function (e) {
            $.ajax({
                type: 'GET',
                url: "/Item/GetItem",
                dataType: 'json',
                data: { codeitem: $(this).find('option:selected').val() },
                success: function (response) {
                    $('#example1').hide();
                    $('#example1 tbody').empty();
                    $.each(response, function (i, item) {
                        var rows = "<tr>" +
                            "<td>" + item.CodeItem + "</td>" +
                            "<td>" + item.Descriptionitem + "</td>" +
                            "<td>" + item.Section + "</td>" +
                            "<td>" + item.BaleSize + "</td>" +
                            "<td>" + item.weight + "</td>" +
                            "<td>" + item.UOM + "</td>" +
                            "<td><a id='lnkView' href='javascript:void(0);'>View</a></td>" +
                            "</tr>";
                        $('#example1 tbody').append(rows);
                    });
                    $('#example1').show();
                },
                error: function () {
                }
            });
        });
    });

    $(function () {
        $.ajax({
            type: 'GET',
            url: "/Item/SelectItem",
            dataType: 'json',
            data: {},
            success: function (response) {
                $('#example1 tbody').empty();
                $.each(response, function (i, item) {
                    var rows = "<tr>" +
                        "<td>" + item.CodeItem + "</td>" +
                        "<td>" + item.Descriptionitem + "</td>" +
                        "<td>" + item.Section + "</td>" +
                        "<td>" + item.BaleSize + "</td>" +
                        "<td>" + item.weight + "</td>" +
                        "<td>" + item.UOM + "</td>" +
                        "<td><a id='lnkView' href='javascript:void(0);'>View</a></td>" +
                        "</tr>";
                    $('#example1 tbody').append(rows);
                });
                $('#example1').show();
            },
            error: function () {
            }
        });

        $('body').on('click', '#example1 tbody tr', function () {
            $("#item_Name").val($(this).find('td').eq(1).html());
       
            $("#select2-1").val($(this).find('td').eq(2).html());
           
        });
    });
</script>

Controller

using ERP_APP.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using DataBaseLayer;

namespace ERP_APP.Controllers
{
    public class ItemController : Controller
    {
        SilverProductionEntities DB = new SilverProductionEntities();
        // GET: Item
        ItemModelDal sdb = new ItemModelDal();
        public ActionResult CreateItem()
        {
            ModelState.Clear();
            ItemModel item = new ItemModel();
       
            //For Loading Data
            
            item.Itemss = sdb.GetItem();
            var cID = 0;
            var secID = 0;
            var codeitEM = 0;
            ViewBag.cID = new SelectList(DB.Catagories.Where(bt => bt.CID > cID), "CID", "CName", "0");
            ViewBag.SecId = new SelectList(DB.Sections.Where(bt => bt.SecID > secID), "SecID", "Secnam", "0");
            ViewBag.codeitem = new SelectList(DB.ItemMasterFiles.Where(bt => bt.CodeItem > codeitEM), "codeitem", "Descriptionitem", "0");
            return View(item);

        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateItem(ItemModel objmod)
        {
            try
            {
                int result = sdb.CreateItem(objmod);
                if (result == 1)
                {
                    ViewBag.Message = "Role Added Successfully";
                    ModelState.Clear();
                }
                else if (result == -1)
                {
                    ViewBag.Message = "Role Already Exists!";
                    ModelState.Clear();
                }
                else
                {
                    ViewBag.Message = "Unsucessfull";
                    ModelState.Clear();
                }

                return RedirectToAction("CreateItem");
            }
            catch
            {
                throw;
            }
        }


        public JsonResult GetItem(string codeitem)
        {
            List<ItemModel> items = new List<ItemModel>();
    
            using (SqlConnection con = new SqlConnection("data source=SERVER1\\SQLEXPRESS;initial catalog=SilverProduction;integrated security=True;MultipleActiveResultSets=True;"))
            {
                string query = "SELECT I.Codeitem,I.Descriptionitem,S.Secnam Section,I.weight,I.BaleSize,U.NameUOM UOM FROM ItemMasterFile I inner join Sections S on S.Secid=I.SecId inner join UOM U on U.IDUOM=I.IDUOM  where I.codeitem=@codeitem";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Codeitem", codeitem);
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            items.Add(new ItemModel
                            {
                                CodeItem = Convert.ToInt32(sdr["CodeItem"]),
                                Descriptionitem = Convert.ToString(sdr["Descriptionitem"]),
                                Section = Convert.ToString(sdr["Section"]),
                                weight = Convert.ToInt32(sdr["weight"]),
                                BaleSize = Convert.ToString(sdr["BaleSize"]),
                                UOM = Convert.ToString(sdr["UOM"]),
                            });
                        }
                    }
                    con.Close();
                }
            }
           
            var jsonResult = Json(items, JsonRequestBehavior.AllowGet);
            return jsonResult;


        }


   
            public JsonResult SelectItem()
        {
           
            
                return Json(DB.ItemMasterFiles.Take(0).ToList(), JsonRequestBehavior.AllowGet);
            }
        }
    }

Developer technologies | ASP.NET | Other
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. AgaveJoe 30,411 Reputation points
    2023-03-01T14:03:56.7066667+00:00

    i got frustrated ,do not know ,where i am making mistake,

    As far as I can tell you lack basic troubleshooting skills. You know the problem starts with the client side code (jQuery/JavaScript) and you can easily reproduce the problem. The first step is reviewing the HTML.

    Right click the select2-1 (dropdown) in the browser and select "Inspect". Right click the select HTML and pick "Copy Element" Paste the HTML on the forum. I assume select2-1 is the select causing the problem.

    <select class="form-control" id="select2-1" name="SecId">
        <option value="">Select</option>
        <option value="1">SecId 1</option>
        <option value="2">SecId 2</option>
        <option value="3">SecId 3</option>
    </select>
    

    Next, right click the HTML table and copy the HTML table here on the forum.

    <table id="example1" class="table table-bordered table-striped">
       <thead>
          <tr>
             <th>ID</th>
             <th>Item Name</th>
             <th>Section</th>
             <th>BaleSize</th>
             <th>weight</th>
             <th>UOM</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <tr>
             <td>1</td>
             <td>Description 1</td>
             <td>1</td>
             <td>96</td>
             <td>10</td>
             <td>1</td>
             <td><a id="lnkView" href="javascript:void(0);">View</a></td>
          </tr>
          <tr>
             <td>2</td>
             <td>Description 1</td>
             <td>2</td>
             <td>55</td>
             <td>20</td>
             <td>2</td>
             <td><a id="lnkView" href="javascript:void(0);">View</a></td>
          </tr>
          <tr>
             <td>3</td>
             <td>Description 3</td>
             <td>3</td>
             <td>54</td>
             <td>40</td>
             <td>3</td>
             <td><a id="lnkView" href="javascript:void(0);">View</a></td>
          </tr>
       </tbody>
       <tfoot>
       </tfoot>
    </table>
    

    Finally, copy the jQuery/JavaScript click event and paste it here on the forum.

    $('body').on('click', '#example1 tbody tr', function () {
        $("#item_Name").val($(this).find('td').eq(1).html());
        $("#select2-1").val($(this).find('td').eq(2).html());
        $("#BaleSize").val($(this).find('td').eq(3).text());
        $("#weight").val($(this).find('td').eq(4).text());
        $("#IDUOM").val($(this).find('td').eq(5).text());
        $("#select2-3").val($(this).find('td').eq(0).text());
        $("#select2-2").val($(this).find('td').eq(0).text());
    });
    

    This is all the information needed to start troubleshooting. The HTML table has the source value the select needs. All we have to do is compare table cells content to the select options. First, we look at the jQuery/JavaScript to find the column index used to fetch the value from the HTML table. From the index we find the column. The index is base zero so the first column is zero.

    Next, we take a look at the column values and compare the column values to the select's option values. There should be a match between the column values and the option values. If there is no match check if the column value matches the option text. If you are matching text then you need the code I posted above which queries the select to find the value given the text.

      <script>
            $('body').on('click', '#example1 tbody tr', function () {
    
                //Get and show the value in the console. 
                var item = $(this).find('td').eq(0).text();
                console.log(item);
    
                //Get the value from the select
                var val = $('#select2-1 option').filter(function () { return $(this).html() == item }).val();
                console.log(val);
    
                $("#select2-1").val(val);
            });
        </script>
    

    If there are no matches then you have other design issues.


5 additional answers

Sort by: Most helpful
  1. AgaveJoe 30,411 Reputation points
    2023-03-01T21:48:16.81+00:00

    i check in console in chrome, but no error is coming their for dropdown list

    As I understand, the problem is clicking a row does not set the select with id=select2-1. All the other controls are populated properly.

    The first step is reviewing the HTML in the browser's dev tools.

    Right click select2-1 and select "Inspect". Right click the select HTML-> copy -> Copy element. Paste the HTML into a response to this post.

    Example

    <select class="form-control" id="select2-1" name="SecId">
        <option value="">Select</option>
        <option value="1">SecId 1</option>
        <option value="2">SecId 2</option>
        <option value="3">SecId 3</option>
    </select>
    

    Right click the table and select "Inspect". Right click the table HTML-> copy -> Copy element. Paste the HTML into a response to this post.

    Example

    <table id="example1" class="table table-bordered table-striped">
       <thead>
          <tr>
             <th>ID</th>
             <th>Item Name</th>
             <th>Section</th>
             <th>BaleSize</th>
             <th>weight</th>
             <th>UOM</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <tr>
             <td>1</td>
             <td>Description 1</td>
             <td>1</td>
             <td>96</td>
             <td>10</td>
             <td>1</td>
             <td><a id="lnkView" href="javascript:void(0);">View</a></td>
          </tr>
          <tr>
             <td>2</td>
             <td>Description 1</td>
             <td>2</td>
             <td>55</td>
             <td>20</td>
             <td>2</td>
             <td><a id="lnkView" href="javascript:void(0);">View</a></td>
          </tr>
          <tr>
             <td>3</td>
             <td>Description 3</td>
             <td>3</td>
             <td>54</td>
             <td>40</td>
             <td>3</td>
             <td><a id="lnkView" href="javascript:void(0);">View</a></td>
          </tr>
       </tbody>
       <tfoot>
       </tfoot>
    </table>
    

    Copy the jQuery/JavaScript click event you are currently using.

    Example

    $('body').on('click', '#example1 tbody tr', function () {
        $("#item_Name").val($(this).find('td').eq(1).html());
        $("#select2-1").val($(this).find('td').eq(2).html());
        $("#BaleSize").val($(this).find('td').eq(3).text());
        $("#weight").val($(this).find('td').eq(4).text());
        $("#IDUOM").val($(this).find('td').eq(5).text());
        $("#select2-3").val($(this).find('td').eq(0).text());
        $("#select2-2").val($(this).find('td').eq(0).text());
    });
    

    The rest is trivial. You looking for the column index select2-1 is using to set the .val(). Compare the column values to the select's option values? Do they match? Do they even exist?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.