Update dropdown value in database from webgrid

Analyst_SQL 3,576 Reputation points
2023-11-03T10:17:00.5833333+00:00

How to update dropdown value from webgrid into database .i tried but it is updating null value

@model IEnumerable<Account_App.Models.CustomerMV>

@{
    Layout = null;
    WebGrid webGrid = new WebGrid(source: Model, canPage: true, canSort: false);
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        .Grid {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }

            .Grid th {
                background-color: #F7F7F7;
                font-weight: bold;
            }

            .Grid th, .Grid td {
                padding: 5px;
                width: 150px;
                border: 1px solid #ccc;
            }

            .Grid, .Grid table td {
                border: 0px solid #ccc;
            }

                .Grid th a, .Grid th a:visited {
                    color: #333;
                }
    </style>
</head>
<body>
    @webGrid.GetHtml(
    htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
    columns: webGrid.Columns(
     webGrid.Column(header: "Customer Id", format: @<span class="label">@item.CustomerId</span>, style: "CustomerId"),
                          webGrid.Column(header: "Name", format: @<span> <span class="label">@item.Name</span> <input class="text" type="text" value="@item.Name" style="display:none" /> </span>, style: "Name"),
                                             webGrid.Column(header: "Country", format: @<span><span class="label">@item.Country</span> <input class="text" type="text" value="@item.Country" style="display:none" /></span>, style: "Country"),


                    //webGrid.Column(header: "UserName", format:  @item => Html.DropDownList("UserName", (IEnumerable<SelectListItem>)ViewBag.U_ID)),
                    webGrid.Column(header: "User", format:
                    @<span>
                        <span class="label">@item.UserName</span>
                        <span class="text" style="display:none"> @Html.DropDownList("UserName", (IEnumerable<SelectListItem>)ViewBag.U_ID)</span>
                    </span>, style: "User"),


                                                                                                         webGrid.Column(format:@<span class="link"><a class="Edit" href="javascript:;">Edit</a><a class="Update" href="javascript:;" style="display:none">Update</a><a class="Cancel" href="javascript:;" style="display:none">Cancel</a></span>)))

    <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 type="text/javascript">
        //Edit event handler.
        $("body").on("click", "#WebGrid TBODY .Edit", function () {
            var row = $(this).closest("tr");
            $("td", row).each(function () {
                if ($(this).find(".text").length > 0) {
                    $(this).find(".text").show();
                    $(this).find(".text").show();
                    $(this).find(".label").hide();
                }
            });
            row.find(".Update").show();
            row.find(".Cancel").show();
            $(this).hide();
        });

        //Update event handler.
        $("body").on("click", "#WebGrid TBODY .Update", function () {
            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");
                    span.html(input.val());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Cancel").hide();
            $(this).hide();

            var customer = {};
            customer.CustomerId = row.find(".CustomerId").find(".label").html();
            customer.Name = row.find(".Name").find(".label").html();
            customer.Country = row.find(".Country").find(".label").html();
            customer.UserID = row.find(".UserID").find(".label").html();
            $.ajax({
                type: "POST",
                url: "/Customer/UpdateCustomer",
                data: '{customer:' + JSON.stringify(customer) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        });

        //Cancel event handler.
        $("body").on("click", "#WebGrid TBODY .Cancel", function () {
            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");
                    input.val(span.html());
                    span.show();
                    input.hide();
                }
            });
            row.find(".Edit").show();
            row.find(".Update").hide();
            $(this).hide();
        });
    </script>
</body>
</html>

Controller

using AADatabaseLayer;
using Account_App.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Account_App.Controllers
{
    public class CustomerController : Controller
    {
        // GET: Customer
        EmpDBEntities DB = new EmpDBEntities();
        public ActionResult Index()
        {

            //List<Customer> customers = DB.Customers.ToList();
            //return View(customers.ToList());

            var custom = DB.Customers.ToList();
            var user = DB.tblUsers.ToList();



            var investerlist = from e in custom
                               join u in user on e.UserID equals u.UserID into table1
                               from u in table1.ToList()
                               select new CustomerMV
                               {
                                  CustomerId=e.CustomerId,
                                  Country=e.Country,
                                  Name=e.Name,
                                  UserName = u.UserName

                               };


            var UserID = 0;
            ViewBag.U_ID = new SelectList(DB.tblUsers.Where(bt => bt.UserID > UserID), "UserID", "UserName", "0");
            return View(investerlist);

        }

        [HttpPost]
        public ActionResult UpdateCustomer(Customer customer)
        {
           
            {
                Customer updatedCustomer = (from c in DB.Customers
                                            where c.CustomerId == customer.CustomerId
                                            select c).FirstOrDefault();
                updatedCustomer.Name = customer.Name;
                updatedCustomer.Country = customer.Country;
                updatedCustomer.UserID = customer.UserID;
                DB.SaveChanges();
            }

            return new EmptyResult();
        }
    }
}
Microsoft 365 and Office | Development | Office JavaScript API
Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,191 Reputation points Microsoft External Staff
    2023-11-06T02:37:51.5366667+00:00

    Hi @Analyst_SQL,

    I tested your code.

    The value of the drop-down box will change. What you need to get is the value of dropdownlist, not the value of .label.

    First, you need to add an Id to the dropdownlist for easy search.

    User's image

    Then get the value of dropdownlist:

    $("#myid option:selected").val();

    The updated content needs to get the text of the dropdownlist:

    $("#myid option:selected").text();

    EDIT1

    <span class="text" style="display:none"> @Html.DropDownList("UserName", new SelectList(ViewBag.U_ID, "UserID", "UserName",selectedValue: @item.UserID), new { @id = "myid"})</span>

    EDIT2

    var drop = $(this).find("#myid option:selected").text();

    customer.UserId = row.find("#myid option:selected").val();

    All Code

    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <style type="text/css">
            body {
                font-family: Arial;
                font-size: 10pt;
            }
    
            .Grid {
                border: 1px solid #ccc;
                border-collapse: collapse;
            }
    
                .Grid th {
                    background-color: #F7F7F7;
                    font-weight: bold;
                }
    
                .Grid th, .Grid td {
                    padding: 5px;
                    width: 150px;
                    border: 1px solid #ccc;
                }
    
                .Grid, .Grid table td {
                    border: 0px solid #ccc;
                }
    
                    .Grid th a, .Grid th a:visited {
                        color: #333;
                    }
        </style>
    </head>
    <body>
        @webGrid.GetHtml(
        htmlAttributes: new { @id = "WebGrid", @class = "Grid" },
        columns: webGrid.Columns(
         webGrid.Column(header: "Customer Id", format: @<span class="label">@item.CustomerId</span>, style: "CustomerId"),
    webGrid.Column(header: "Name", format: @<span> <span class="label">@item.Name</span> <input class="text" type="text" value="@item.Name" style="display:none" /> </span>, style: "Name"),
    webGrid.Column(header: "Country", format: @<span><span class="label">@item.Country</span> <input class="text" type="text" value="@item.Country" style="display:none" /></span>, style: "Country"),
    webGrid.Column(header: "User", format:
    @<span>
        <span class="label">@item.UserName</span>
        <span class="text" style="display:none">
            @Html.DropDownList("UserName", new SelectList(ViewBag.U_ID, "UserID", "UserName", selectedValue: @item.UserID), new { @id = "myid" })
        </span>
    </span>, style: "User"),
    
    
    webGrid.Column(format:@<span class="link"><a class="Edit" href="javascript:;">Edit</a><a class="Update" href="javascript:;" style="display:none">Update</a><a class="Cancel" href="javascript:;" style="display:none">Cancel</a></span>)))
    
        <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 type="text/javascript">
            //Edit event handler.
            $("body").on("click", "#WebGrid TBODY .Edit", function () {
                var row = $(this).closest("tr");
                $("td", row).each(function () {
                    if ($(this).find(".text").length > 0) {
                        $(this).find(".text").show();
                        $(this).find(".label").hide();
                    }
                });
                row.find(".Update").show();
                row.find(".Cancel").show();
                $(this).hide();
            });
    
            //Update event handler.
            $("body").on("click", "#WebGrid TBODY .Update", function () {
                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");
                        var drop = $(this).find("#myid option:selected").text();
                        span.html(input.val());
                        row.find(".User").find(".label").html(drop);
                        span.show();
                        input.hide();
                    }
                });
                row.find(".Edit").show();
                row.find(".Cancel").hide();
                $(this).hide();
    
                var customer = {};
                customer.CustomerId = row.find(".CustomerId").find(".label").html();
                customer.Name = row.find(".Name").find(".label").html();
                customer.Country = row.find(".Country").find(".label").html();
                customer.UserId = row.find("#myid option:selected").val();
                $.ajax({
                    type: "POST",
                    url: "/Customer/UpdateCustomer",
                    data: '{customer:' + JSON.stringify(customer) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                });
            });
    
            //Cancel event handler.
            $("body").on("click", "#WebGrid TBODY .Cancel", function () {
                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");
                        input.val(span.html());
                        span.show();
                        input.hide();
                    }
                });
                row.find(".Edit").show();
                row.find(".Update").hide();
                $(this).hide();
            });
        </script>
    </body>
    </html>
    
     public ActionResult Index()
     {
         var custom = DB.Customers.ToList();
         var user = DB.tblUsers.ToList();
         var investerlist = from e in custom
                            join u in user on e.UserID equals u.UserID into table1
                            from u in table1.ToList()
                            select new CustomerMV
                            {
                                CustomerId = e.CustomerId,
                                Country = e.Country,
                                Name = e.Name,
                                UserName = u.UserName,
                                UserID = u.UserID,
                            };
         var UserID = 0;
         ViewBag.U_ID = DB.tblUsers.Where(bt => bt.UserID > UserID);
         return View(investerlist);
     }
    
     [HttpPost]
     public ActionResult UpdateCustomer(Customer customer)
     {
    
    
         Customer updatedCustomer = (from c in DB.Customers
                                     where c.CustomerId == customer.CustomerId
                                     select c).FirstOrDefault();
         updatedCustomer.Name = customer.Name;
         updatedCustomer.Country = customer.Country;
         updatedCustomer.UserID = customer.UserID;
    
         DB.SaveChanges();
    
    
         return new EmptyResult();
     }
    

    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

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.