skip to Main Content

When I select dropdownlist I want to retrieve data from database according to dropdownlist ID.

The whole row is retrieved through an ajax call and I only want PurchasePrice and RemainingQuantity to display through label in view.

Second is: I want to update tbl_addproduct when user give some date from input text I created a function in jQuery but don’t know how to update table row through PID.

Like previously I used in ASP.NET

update tbl_AddProduct 
set Date = @date 
where PID = @pid

I have two model classes:

public class addproduct
{
    public int PID { get; set; }
    public int VID { get; set; }
    public string ProductName { get; set; }
    public decimal ProductQuantity { get; set; }
    public decimal PurchasePrice { get; set; }
    public decimal SellingPrice { get; set; }
    public decimal RemainingQuantity { get; set; }
    public DateTime Date { get; set; }
    public int SID { get; set; }
    public Boolean Paid { get; set; }
}

Second view model. through this performing cascading dropdownlist

public class vendorproductVM
{
    public addproduct addpro { get; set; }
    public int VID { get; set; }
    public int PID { get; set; }
}

Index view:

        <div class="row">
            <div class="col-sm-6">
                @Html.Label("Vendor Name")
                @if (ViewBag.vendorlist != null)
                {
                    @Html.DropDownListFor(m => m.VID, ViewBag.vendorlist as SelectList, "Select", new { @class = "  form-control" })
                }

            </div>
            <div class="col-sm-6">
                @Html.Label("Product Name")
                @Html.DropDownListFor(m => m.PID, new SelectList(" "), "--Select--", new { @class = "form-control" })

            </div>
        </div>
        <div class="row">


            <div class="col-sm-4">
                @Html.Label("Remaining Quantity")
                @Html.LabelFor(m => m.addpro.RemainingQuantity)
            </div>

            <div class="col-sm-4">
                @Html.Label("Purchase Price")
                @Html.LabelFor(m => m.addpro.PurchasePrice )
            </div>

            <div class="col-sm-4">
                @Html.Label("Date")
                <input type="text" id="txt_date" />
            </div>
        </div>
        <div>
            <div class="col-sm-4" style="align-content: center">
                <input type="button" id="btn_save" value="Save" CssClass="btn btn-success" />
                <input type="button" id="btn_cancel" value="Cancel" CssClass="btn btn-danger" />
            </div>
        </div>
<script>
$(function () {
     $("#VID").change(function () {

        var vid = $("#VID").val();
        $("#PID").empty();
        $.ajax({
            type: "post",
            url: "/ProductInventory/getproductlist",
            //datatype: "Json",
            data: { VID: vid, },
            success: function (products) {
                debugger
                $.each(products, function (index, row) {
                    $("#PID").append("<option value='" + row.PID + "'>" + row.ProductName + "</option>");
                });
                //$("productlist").append();
            },
            failure: function () {
                alert("something goes wrong")
            }
        })
    });

    $(function () {
    $("#btn_save").click(function () {
        $.ajax({
            type: "Post",
            url: "/ProductInventory/updatedate",
            data: {
                date: $("#txt_date").val(),
            },
            success: function (da) {
                alert("updated date successfully");
            },
            failure: function (da) {
                alert("error");
            },
        })
   })
})

$("#PID").change(function () {
        var pid = $("#PID").val();

        $.ajax({
            type: "post",
            url: "/ProductInventory/getremaining",
            data: { PID: pid },
            success: (function (data) {
                debugger
                $.each(data, function (index, value) {
                // I want to show remaining amount and purchase price in label 
                // and I tried below code this 
                $("#lblremquantity").html(parseInt(value.RemainingQuantity))
                    //$("#RemaingQuantity").append("<label value='" + value.PID + "'>" + 
                    value.RemaingQuantity + "</label>");
                });
            })
        })
    });
})
</script>

My controller:

public class ProductInventoryController : Controller
{
    private db_shopEntities db = new db_shopEntities();

    // GET: ProductInventory
    public ActionResult Index()
    {
        ViewBag.vendorlist = new SelectList(getvendorlist(), "VID", "VendorName");
        return View();
    }

    public List<tbl_AddVendor> getvendorlist()
    {
       List<tbl_AddVendor> vendors = db.tbl_AddVendor.ToList();
       return vendors;
    }

    public JsonResult getproductlist(int VID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        List<tbl_AddProduct> products = db.tbl_AddProduct.Where(x => x.VID == VID).ToList();
        var pro = products;
        // ViewBag.productlist = new SelectList(products, "VID", "VendorName");
        return Json(products, JsonRequestBehavior.AllowGet);
    }

    public JsonResult getremainingquantity(int PID)
    {
        db.Configuration.ProxyCreationEnabled = false;

        List<tbl_AddProduct> remquantity = db.tbl_AddProduct.Where(x => x.PID == PID).ToList();
        return Json(remquantity, JsonRequestBehavior.AllowGet);
    }

    public JsonResult updatedate(string date)
    {
        DateTime sdate = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
        db.Configuration.ProxyCreationEnabled = false;

        // I want to update tbl_addproduct.. update date column when submit
        return Json(success, JsonRequestBehavior.AllowGet);
    }
}

2

Answers


  1. If I am understanding your request, then an easy way to do this would be to utilize the Microsoft jQuery Unobtrusive Ajax Nuget Package.

    Using this, you could set up your dropdowns within the Ajax submit form and have the submission update a targeted DIV id with new data from a partial view.

    to do so, you would need to install it via the Nuget Package Manager and enter the following in your view:

    @{using (Ajax.BeginForm("Metadata", "Applications", null, new AjaxOptions
         {
              HttpMethod = "POST",
              UpdateTargetId = "DivID",
              InsertionMode = InsertionMode.Replace,
              // ...
         }))
         {
              // Html Code (DropdownList) Here (within form)
         }}
    // At the end of your view:
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    

    This way, you can have a PartialViewResult on your controller side to load new data within a div you designate on the master page.

    Additional resources:

    YouTube

    Tutorial

    Login or Signup to reply.
  2. if this a new project maybe you try blazor ?

    also you can use jquery but this is not a modern approach

    $.ajax({
        //type: 'post',
        url: 'http://///////',
        data: { 'filter': JSON.stringify(filter) },
        success: function (data) {
            callback(data);
        },
        error: function (ex, textStatus, errorThrown) {
            SetAlert('Помилка доступу до сервера ' + textStatus + '  ' + errorThrown, 'danger', false);
    
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search