Search code examples
c#jqueryasp.net-mvcwebgrid

How do you move data from one cell in one row of a web grid to another cell in another row that is empty using jQuery?


I am kind of lost when it comes to jQuery sometimes, though I know there is a way! How do you update or move three cells data to another row based on the rows id to where the row is green (empty cells)? The row column ID name is "LocationID". MVC application using a web grid. What I am trying to do is when I check the row, use the drop-down that has the id, send the data to that row where the id exists populating the three empty cells in green with the current columnar data row that is checked. Any help would be greatly appreciated!

enter image description here

WebGrid below:

enter 
            <div id="content">
                @webGrid.GetHtml(tableStyle: "webgrid-table",
  headerStyle: "webgrid-header",
  footerStyle: "webgrid-footer",
  //alternatingRowStyle: "webgrid-alternating-row",
  selectedRowStyle: "webgrid-selected-row",
  rowStyle: "webgrid-row-style",
  mode: WebGridPagerModes.All,
  htmlAttributes: new { @id = "webGrid" },
  columns: webGrid.Columns(
  webGrid.Column(header: "Actions", format:@<span class="link">
        <!--Add Checkbox here-->
        <!-- Note: We can add clickable rows as an option for user using a checkbox, one 
  selects the data move and the other move to selection. -->
        @Html.CheckBoxFor(model => model.SelectedMoveIsChecked, new { @Class = 
 "SelectedMoveIsChecked", @id = "SelectedMoveIsChecked", @checked = false })
        @Html.CheckBoxFor(model => model.SelectedMoveToChecked, new { @Class = 
 "SelectedMoveToChecked", @id = "SelectedMoveToChecked", @checked = false })

        <!-- Html.CheckBox("isActive", false, item.isSelectdRow, true, new { id = 
 "CheckBoxSelectedBeginMove", Class = "CheckBoxIsSelected" })
        Html.CheckBoxFor(Model.Input_Location, item.isSelectdRow, new {  = "'SelectedRows'", 
 data_val = item.Location })
            -->
        <a class="Edit" href="javascript:;">Edit</a>
        <a class="Clear" href="javascript:;">Clear</a>
        <a class="Update" href="javascript:;" style="display:none">Update</a>
        <a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
    </span>),

 webGrid.Column(header: "Location", format: @<div>
    <label id="LocationLbl" class="label">@item.Location</label>
    <input id="Location" class="text" type="text" value="@item.Location" style="display:none" 
/><br />
    @Html.DropDownListFor(model => model.LocationAppended, Model.LocationAppended, 
"Section/Location", new { IReadOnlyDictionary = "document.forms[0].submit();", @id = 
"RowLocationDropDownList", @class = "RowLocationDropDownList", @visibility = "hidden", 
@placeholder = "Location" })
</div>, style: "Location"),

webGrid.Column(header: "Section", format: @<div>
<label id="SectionLbl" class="label">@item.Section</label>
<input id="Section" class="text" type="text" value="@item.Section" style="display:none" />

</div>, style: "Section"),

webGrid.Column(header: "TrailerNumber", format: @<div>
<label id="TrailerNumberLbl" class="label">@item.TrailerNumber</label>
<input id="TrailerNumber" class="text" type="text" value="@item.TrailerNumber" 
style="display:none" />
</div>, style: "TrailerNumber"),

webGrid.Column(header: "CarrierName", format: @<div>
<label id="CarrierNameLbl" class="label">@item.CarrierName</label>
<input id="CarrierName" class="text" type="text" value="@item.CarrierName" 
style="display:none" />
</div>, style: "CarrierName"),

webGrid.Column(header: "LoadCommodityStatus", format: @<div>
<label id="LoadCommodityStatusLbl" class="label">@item.LoadCommodityStatus</label>
<input id="LoadCommodityStatus" class="text" type="text" value="@item.LoadCommodityStatus" 
style="display:none" />
</div>, style: "LoadCommodityStatus"),

webGrid.Column(header: "DateLoaded", format: @<div>
<label id="DateLoadedLbl" class="label">@item.DateLoaded</label>
<input id="DateLoaded" class="text" type="text" value="@item.DateLoaded" style="display:none" 
/>
</div>, style: "DateLoaded"),

webGrid.Column(header: "UserName", format: @<div>
<label id="UserNameLbl" class="label">@item.UserName</label>
<input id="UserName" class="text" type="text" value="@item.UserName" style="display:none" />
</div>, style: "UserName"),

webGrid.Column(header: "PlantLocation", format: @<div>
<label id="PlantLocationLbl" class="label">@item.PlantLocation</label>
<input id="PlantLocation" class="text" type="text" value="@item.PlantLocation" 
style="display:none" />
</div>, style: "PlantLocation"),

webGrid.Column(header: "RowPageID", format: @<div>
<label id="LocationIDLbl" class="label">@item.LocationID</label>
</div>, style: "LocationID"))),

                <div id="RowCountBpttom"><b>Records: @firstRecord - @lastRecord of 
   @webGrid.TotalRowCount</b></div>
            </div>
            <br />
            <div class="WebGridTable">

            </div>
        </div>

    </form>
</div>
<script type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"> 
</script>
<script src="~/Scripts/YardDogAdmin.js"></script>

 </body>

jQuery Below:

code here

enter 

$('select.RowLocationDropDownList').attr('disabled', true);

$(".SelectedMoveIsChecked").change(function (i, row) {

    $actualRowColorRed = $(row);
    
//When a value is selected in the dropdownlist box.
if ($(this).children("option:selected").val() != '') {

    $("select.RowLocationDropDownList").change(function (i, row) {

        $actualRowColorRed = $(row);

        //Checks to see if the checkbox is checked, display the alert showing data and color the row red again.
        /////// if ($('.SelectedMoveIsChecked').is(':checked') == true) {

        $('select.RowLocationDropDownList').children("option:selected").val();
        var str = $(this).children("option:selected").val();
        var ret = str.split(" ");
        var RowLocationID = ret[0];
        var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
        var RowSection = ret[1];
        var RowLocation = ret[2];


        var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
        var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
        var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
        var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
        var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
        var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
        var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
        var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
        var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();


      //  var ConfirmStr = " <b>Are you sure, you want to move this row From: </b>" + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
       // alert("Alert " + ConfirmStr + "Original: " + str + "  RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?"
            
      //  );
        
        function Confirm() {
            var confirm_value = document.createElement("INPUT");
            confirm_value.type = "hidden";
            confirm_value.name = "confirm_value";
            var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
            if (confirm("Confirm! " + ConfirmStr + "Original: " + str + "  RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
                confirm_value.value = "Yes";

                //Add new values to (TrailerNumber, CarrierName, LoadCommodityStatus, DateLoaded, UserName). 
                //Note: Get the UserName currently using the Yard Dog Application. 

             /// $('#webGrid').closest('tr').find('#TrailerNumber').val();
               /// $("#webGrid tbody tr").each(function (i, row) {

              
              //  $('#webGrid tbody tr').find('#LocationID'.val(RowLocationIDNum); //= RowLocationIDNum).append('#TrailerNumber'.val(CurrentRowTrailerNumber));
                $("body").on("change", "select.RowLocationDropDownList", function () {
                   // $("body").on("click", "#webGrid TBODY .Update", function () {
                    //  $("#content").on("click", "#webGrid INPUT", function () {
                    var row = $(this).closest("tr");
                    $("webGrid td", row).each(function () {
                        if ($(this).find(".text").length > 0) {
                            var span = $(this).find(".label");
                            var input = $(this).find(".text");
                            span.html(input.val());

                        }
                    });



                    ////  $('#webGrid tbody tr').find('#LocationID').val(RowLocationIDNum) = customer;
                    var RowExchange = $(RowLocationID).closest("tr");

                    var ToRow = {};
                    
                    ToRow.LocationID = row.find(".LocationID").find(".label").html();
                    ToRow.UserName = row.find(".UserName").find(".label").html();
                    ToRow.Location = row.find(".Location").find(".label").html();
                    ToRow.Section = row.find(".Section").find(".label").html();
                    ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
                    ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
                    ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
                    ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
                    ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
                    
                    
                    /*
                    ToRow.LocationID = RowExchange.find('#LocationID').append(RowLocationID) ;
                    ToRow.UserName = RowExchange.find('.UserName').append(row.find(".UserName").find(".label").html());
                    ToRow.Location = RowExchange.find('.Location').append(row.find(".Location").find(".label").html());
                    ToRow.Section = RowExchange.find('.Section').append(row.find(".Section").find(".label").html());
                    ToRow.TrailerNumber = RowExchange.find('.TrailerNumber').append(ToRow.TrailerNumber);
                    ToRow.CarrierName = RowExchange.find('.CarrierName').val().append(ToRow.CarrierName);
                    ToRow.LoadCommodityStatus = RowExchange.find('.LoadCommodityStatus').append(ToRow.LoadCommodityStatus);
                    ToRow.DateLoaded = RowExchange.find('.DateLoaded').append(row.find(".DateLoaded").find(".label").html());
                    ToRow.PlantLocation = RowExchange.find('.PlantLocation').append(row.find(".PlantLocation").find(".label").html());
                    */
                    $.ajax({
                        type: "POST",
                        url: "/Home/UpdateRowExchange",
                        data: '{ToRow:' + JSON.stringify(ToRow) +'}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json"
                    }); setInterval('location.reload()', 777);

                });
            }
            else {
               
                confirm_value.value = "Cancel";
            }
            
            document.forms[0].appendChild(confirm_value);
        }
        Confirm();
       code here

Controller:

enter        [HttpPost]
    public ActionResult UpdateRowExchange(LocationData ToRow)
    {
        using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
        {
            LocationData updatedCustomer = (from c in entities.LocationDatas
                                            where c.LocationID == ToRow.LocationID
                                            select c).FirstOrDefault();


            //Check for Duplicates.
            ///FindDuplicates(customer);
            //HighlightDuplicate(webGrid);

            //x => customer.TrailerNumber == x.TrailerNumber && x.TrailerNumber == customer.TrailerNumber //errases all data except the first cell TrailerNumber.
            if (ToRow.UserName != null) updatedCustomer.UserName = ToRow.UserName.ToUpper();
            else updatedCustomer.UserName = ToRow.UserName = null;
            /*
            if (customer.Location != null) updatedCustomer.Location = customer.Location.ToUpper();
            else updatedCustomer.Location = customer.Location = null;

            if (customer.Section != null) updatedCustomer.Section = customer.Section.ToUpper();
            else updatedCustomer.Section = customer.Section = null;
            */
            if (ToRow.TrailerNumber != null) updatedCustomer.TrailerNumber = ToRow.TrailerNumber.ToUpper();
            else updatedCustomer.TrailerNumber = ToRow.TrailerNumber = null;

            if (ToRow.CarrierName != null) updatedCustomer.CarrierName = ToRow.CarrierName.ToUpper();
            else updatedCustomer.CarrierName = ToRow.CarrierName = null;

            if (ToRow.LoadCommodityStatus != null) updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus.ToUpper();
            else updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus = null;

            if (ToRow.DateLoaded != null) updatedCustomer.DateLoaded = ToRow.DateLoaded.ToUpper();
            else updatedCustomer.DateLoaded = ToRow.DateLoaded = null;
            /*
            if (customer.PlantLocation != null) updatedCustomer.PlantLocation = customer.PlantLocation.ToUpper();
            else updatedCustomer.PlantLocation = customer.PlantLocation = null;
            */


            //Create today's Date for a timestamp of inputs. 

            DateTime now = DateTime.Today;
            ToRow.DateLoaded = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
            updatedCustomer.DateLoaded = ToRow.DateLoaded;

            entities.SaveChanges();
            //Refresh(out, customer.ToString());
        }
        return new EmptyResult();
    }

code here

Model below:

enter code here

namespace YardDog.Model
{

public class YardDogModel
{
    ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
    //Two Properties for DropDownList.
    public List<LocationData> LocationDatas { get; set; }
    //public List<LocationData> Location { get; set; }
    public List<LocationData> TrailerNumber { get; set; }
    public List<SelectListItem> PlantLocation { get; set; }

    public List<SelectListItem> Location { get; set; }
    
    public List<SelectListItem> LocationList { get; set; }
    public List<SelectListItem> SectionList { get; set; }

    public List<SelectListItem> LocationAppended { get; set; }

    [Display(Name = "Name")]
    public List<SelectListItem> Section { get; set; }
    
    public List<SelectListItem> ListDuplicates { get; set; }
    public List<SelectListItem> UserName { get; set; }
   



    //Allow the data to be transfered (Backend into SQL Server).
    [Required]
    public string Input_Location { get; set; }

    [Required]
    public string Input_Section { get; set; }
    
    public string Input_TrailerNumber { get; set; }
    
    public string Input_CarrierName { get; set; }
    public string Input_CommodityLoadStatus { get; set; }

    [Required]
    public string Input_PlantLocation { get; set; }

    //YardDogModel YardDogDatas = new YardDogModel();
    //string TrailerNumber = Input_TrailerNumber;

    public bool SelectedMoveIsChecked { get; set; } = false;
    public bool SelectedMoveToChecked { get; set; } = false;
    public string LocationAppendedLbl { get; internal set; }
    //public string LocationAppended { get; internal set; }
    public string RowLocationDropDownList { get; set; }

    public int RowLocationIDNum { get; set; }

    
}
 }

Solution

  • JavaScript:

                $('select.RowLocationDropDownList').children("option:selected").val();
                var str = $(this).children("option:selected").val();
                var ret = str.split(" ");
                var RowLocationID = ret[2];
                var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
                var RowSection = ret[0];
                var RowLocation = ret[1];
    
                var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
                var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
                var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
                var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
                var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
                var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
                var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
                var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
                var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
    
                function Confirm() {
                    var confirm_value = document.createElement("INPUT");
                    confirm_value.type = "hidden";
                    confirm_value.name = "confirm_value";
                    var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
                    if (confirm("Confirm! " + ConfirmStr + "Original: " + str + "  RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
                        confirm_value.value = "Yes";
    
                        $("body").on("change", "select.RowLocationDropDownList", function () {
                            var row = $(this).closest("tr");
                            $("webGrid td", row).each(function () {
                                if ($(this).find(".text").length > 0) {
                                    span.html(input.val());
                                }
                            });
    
                            //Tell the row change to be where ID exists by ID Number (RowLocationIDNum).
                            var ToRow = {};
                            ToRow.LocationID = RowLocationIDNum; //row.find(".LocationID").find(".label").html();
                            ToRow.UserName = row.find(".UserName").find(".label").html();
                            ToRow.Location = row.find(".Location").find(".label").html();
                            ToRow.Section = row.find(".Section").find(".label").html();
                            ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
                            ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
                            ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
                            ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
                            ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
    
                            $.ajax({
                                type: "POST",
                                url: "/Home/UpdateRowExchange",
                                data: '{ToRow:' + JSON.stringify(ToRow) + '}',
                                contentType: "application/json; charset=utf-8",
                                dataType: "json"
                            });
    
                            // setInterval('location.reload()', 777);
                            //Set the Clear Event to clear the initial rows. 
                            var row = $(this).closest("tr");
                            $("td", row).each(function () {
                                if ($(this).find(".text").length > 0) {
                                    var span = $(this).find(".label");
                                    var input = $(this).find(".text");
                                    $(this).find(".text").show();
                                    $(this).find(".label").hide();
                                    span.html(input.val(null));
                                    span.show();
                                    input.hide();
                                }
                            });
                            row.find(".Cancel").show();
                            row.find(".Clear").show();
                            row.find(".Edit").show();
                            $(this).hide();
                            var clear = {};
                            clear.LocationID = row.find(".LocationID").find(".label").html();
                            clear.UserName = row.find(".UserName").find(".label").html();
                            clear.Location = row.find(".Location").find(".label").html();
                            clear.Section = row.find(".Section").find(".label").html();
                            clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
                            clear.CarrierName = row.find(".CarrierName").find(".label").html();
                            clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
                            clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
                            clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
                            $.ajax({
                                type: "POST",
                                url: "/Home/ClearCustomer",
                                data: '{clear:' + JSON.stringify(clear) + '}',
                                contentType: "application/json; charset=utf-8",
                                dataType: "json"
                            }); setInterval('location.reload()', 500);
    
                        });
                    }
                    else {
    
                        confirm_value.value = "Cancel";
                        setInterval('location.reload()', 500);
                    }
    
                    document.forms[0].appendChild(confirm_value);
                }
                Confirm();
    
            });
    
        }
    });