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#
{count} votes

Accepted answer
  1. AgaveJoe 30,126 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,126 Reputation points
    2023-02-25T17:07:31.2133333+00:00

    I did my best to create a test based on your unfinished code. As far as I can tell, the reason only 2 inputs are populated is because you did not write any code that sets the other input values?!

    @model MvcBasic.Controllers.ItemModel
    @{
        ViewBag.Title = "CreaterItem";
        Layout = "~/Views/Shared/_Layout.cshtml";
    
    }
    
    <h2>Index</h2>
    
    
    <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>*@
    
    @section scripts {
        <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());
                    $("#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());
                    
                    
    
                });
            });
        </script>
    }
    
    
    
    
    

    Controller

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MvcBasic.Controllers
    {
        public class ItemModel
        {
            public int weight { get; set; }
            public string CodeItem { get; set; }
            public string Descriptionitem { get; set; }
            public string Section { get; set; }
            public int BaleSize { get; set; }
            public string UOM { get; set; }
    
            public int SecID { get; set; }
            public int  IDUOM { get; set; }
            public int CID { get; set; }
    
            public List<Item> Itemss { get; set; }
        }
    
        public class Item {
            public int weight { get; set; }
            public string CodeItem { get; set; }
            public string Descriptionitem { get; set; }
            public string Section { get; set; }
            public int BaleSize { get; set; }
            public string UOM { get; set; }
        }
    
        public class ItemController : Controller
        {
            private List<Item> MockData;
    
            private List<SelectListItem> cIDData;
            private List<SelectListItem> SecIdData;
            private List<SelectListItem> codeitemData;
    
            private SelectList cID;
            private SelectList SecId;
            private SelectList codeitem;
    
            public ItemController()
            {
                MockData = new List<Item>()
                {
                    new Item()
                    {
                        BaleSize = 96,
                        CodeItem = "1",
                        Descriptionitem = "Description 1",
                        Section = "1",
                        UOM  = "1",
                        weight = 10
                    },
                    new Item(){
                        BaleSize = 55,
                        CodeItem = "2",
                        Descriptionitem = "Description 1",
                        Section = "2",
                        UOM  = "2",
                        weight = 20
                    },
                     new Item(){   
                         BaleSize = 54,
                        CodeItem = "3",
                        Descriptionitem = "Description 3",
                        Section = "3",
                        UOM  = "3",
                        weight = 40
                    },
    
                };
    
                cIDData = new List<SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Value ="1",
                        Text = "CID 1"
                    },
                     new SelectListItem()
                    {
                        Value ="2",
                        Text = "CID 2"
                    },
                      new SelectListItem()
                    {
                        Value ="3",
                        Text = "CID 3"
                    }
                };
    
                SecIdData = new List<SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Value ="1",
                        Text = "SecId 1"
                    },
                     new SelectListItem()
                    {
                        Value ="2",
                        Text = "SecId 2"
                    },
                      new SelectListItem()
                    {
                        Value ="3",
                        Text = "SecId 3"
                    }
                };
    
                codeitemData = new List<SelectListItem>()
                {
                    new SelectListItem()
                    {
                        Value ="1",
                        Text = "codeitem 1"
                    },
                     new SelectListItem()
                    {
                        Value ="2",
                        Text = "codeitem 2"
                    },
                      new SelectListItem()
                    {
                        Value ="3",
                        Text = "codeitem 3"
                    }
                };
    
                cID = new SelectList(cIDData, "Value", "Text");
                SecId = new SelectList(SecIdData, "Value", "Text");
                codeitem = new SelectList(codeitemData, "Value", "Text");
            }
            // GET: Item
            public ActionResult Index()
            {
                ItemModel item = new ItemModel();
                ViewBag.cID = cID;
                ViewBag.SecId = SecId;
                ViewBag.codeitem = codeitem;
                item.Itemss = MockData;
                return View(item);
            }
            public ActionResult CreateItem()
            {
                ItemModel item = new ItemModel();
                ViewBag.cID = cID;
                ViewBag.SecId = SecId;
                ViewBag.codeitem = codeitem;
                item.Itemss = MockData;
                return View(item);
    
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult CreateItem(ItemModel objmod)
            {
                if(!ModelState.IsValid)
                {
                    return View(objmod);
                }
                return RedirectToAction("CreateItem");
            }
    
    
            public JsonResult GetItem(string codeitem)
            {
                var jsonResult = Json(MockData.Where(m => m.CodeItem == codeitem), JsonRequestBehavior.AllowGet);
                return jsonResult;
            }
    
    
    
            public JsonResult SelectItem()
            {
                IEnumerable<Item> jasonResult = MockData.Take(1).ToList();
                return Json(jasonResult, JsonRequestBehavior.AllowGet);
            }
        }
    }
    
    1 person found this answer helpful.

  2. AgaveJoe 30,126 Reputation points
    2023-02-27T14:10:44.74+00:00

    This is your original problem statement.

    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

    Your original code only sets the value of two inputs when a table row was selected; #item_Name and #select2-1. I provided code that sets the other input values when a row is clicked.

    If the problem is a select's options are not populated. That's probably due to you naming the table "Sectionsss" while the entity name is "Sections". Do you have two tables? Sectionsss and Sections????

    ViewBag.SecId = new SelectList(DB.Sections.Where(bt => bt.SecID > secID), "SecID", "Secnam", "0");
    

  3. AgaveJoe 30,126 Reputation points
    2023-02-28T15:14:28.1266667+00:00

    Maybe you are asking how to select a select's option using the text rather than the value????

    Below is an example.

    
    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Index</h2>
    
    <div>
        <select id="select2-1" name="SelId">
            <option value="">-- Select --</option>
            <option value="1">Belt</option>
            <option value="2">Pant</option>
        </select>
    </div>
    
    <div>
        <table id="example1">
            <thead>
                <tr>
                    <th>Item name</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Belt</td>
                </tr>
                <tr>
                    <td>Pant</td>
                </tr>
            </tbody>
        </table>
    </div>
    
    @section scripts
            {
        <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>
    }
    
    

  4. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2023-03-01T07:48:53.46+00:00

    Hi @Analyst_SQL ,
    I tested your code with simple data, and you try to change the eq() of select to 0.

    It may be that the index of eq(index) is inconsistent due to data problems, but the reason should be related to this. You can try changing it to a different number to see.

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

    TEST

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

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