Click here to Skip to main content
15,887,332 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying pass parameter to the Kendo grid.It does pass parameter if its integer "100" and works perfect,but doesn't fire event if its ZZ001.can anyone help?
My code is as below:
C#
@(Html.Kendo().Grid<orderlineview>()
      .Name("OrderLineGrid")
      .Columns(columns =>
      {
          //columns.Bound(p => p.SerialNo);

          columns.Bound(p => p.StockCode).Title("Stock Code").Width(250);
          columns.Bound(p => p.OrderLineDescription).Title("Description");
          columns.Bound(p => p.Quantity).HtmlAttributes(new { style = "text-align:right" });
          columns.Bound(p => p.UnitPrice).Format("{0:c}").HtmlAttributes(new { style = "text-align:right" });
          columns.Bound(p => p.DiscountPercentage).Title("Disc %").Width(70).HtmlAttributes(new { style = "text-align:right" });
          columns.Bound(p => p.DiscountAmount).Title("Discount  ").Format("{0:c}").HtmlAttributes(new { style = "text-align:right" });
          columns.Bound(p => p.TaxRate).HtmlAttributes(new { style = "text-align:right" });
          columns.Bound(p => p.TaxAmount).Title("Tax Amount").Format("{0:c}").HtmlAttributes(new { style = "text-align:right" });
          columns.Bound(p => p.TotalPrice).Format("{0:c}").HtmlAttributes(new { style = "text-align:right" });



          columns.Command(command =>
          {
              command.Edit().UpdateText(" ").CancelText(" ");
              //command.Custom("").Text("History").Click("OpenItemhistoryPopup");
              //command.Custom("Delete").Click("deleteRow");
              command.Destroy();
          }).Width(170);

          columns.Bound("").ClientTemplate("<input type='button' onclick='OpenItemhistoryPopup(#=StockCode #)' value='History' ></input>");

      })
      .ToolBar(toolbar => toolbar.Create())


      .Editable(editable => editable.Mode(GridEditMode.InLine)
      //.CreateAt(GridInsertRowPosition.Bottom)
      )
      //.Pageable()
      //.Sortable()
      //.Scrollable()
      .HtmlAttributes(new { style = "height:430px; overflow-y:scroll" })
      .Events(ev=>ev.Edit("EditGrid")
          .Save("Rearrange")
      )
      .DataSource(dataSource => dataSource
          .Ajax()

          //.Sort(sort => sort.Add("SerialNo"))
          //.PageSize(20)
          //.Events(events => events.Error("error_handler"))
          .Events(e => e.RequestEnd("onRequestEnd"))
          //.Events(e=>e.Push("Rearrange"))
          .Model(model => model.Id(p => p.OrderLineId))
          .Create(update => update.Action("OrderLineCreate", "Order"))
          .Read(read => read.Action("GetAllOrderLines", "Order"))
          .Update(update => update.Action("OrderLineUpdate", "Order"))//.Data("additionalData")
          .Destroy(update => update.Action("OrderLineDelete", "Order"))
          .Events(events =>  events.Error("error_handler"))
      //.Events(events =>  events.Push("Rearrange"))



      ))


JavaScript is as follows:
C#
function OpenItemhistoryPopup(stockCode) {
        try {
          
            if (stockCode == null) {
                return;
            }
                
            //return;
            var url = '@ConfigurationManager.AppSettings["BaseUrl"]Order/ItemPriceHistory?stockCode=' + stockCode;
            $("#windowfritempricehistory").data("kendoWindow").open();
            $("#windowfritempricehistory").data("kendoWindow").refresh(url);
            $("#windowfritempricehistory").data("kendoWindow").center();      

        } catch (e) {
            alert(e);
        }
    }

C# code
public ActionResult Itempricehistorydetails([DataSourceRequest] DataSourceRequest request, string searchvalue)
{
   // searchvalue = "100";
    return Json(Itempricehistorydetails(searchvalue).ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

private IQueryable<Itempricehistory> Itempricehistorydetails(string stockcode)
{
    string city = (string)(Session["password"]);

    int intstockcode = Convert.ToInt32(stockcode);
    SessionContext sessionContext = CurrentSession;
    string myObUrl = sessionContext.Url;
    string myObUser = sessionContext.LogInUserName;
    string myObPassword = city;
    string custcode = sessionContext.CurrentCustomerId;
    string dtfrom = DateTime.Now.AddYears(-1).ToString("dd/MM/yyyy");
    string dateTo = DateTime.Now.ToString("dd/MM/yyyy");


    string url = ConfigurationManager.AppSettings["BaseServiceUrl"] + "Order/GetSalesHistoryByCustomerByInventoryId? &user=" + myObUser + "&password=" + myObPassword + "&customerId=" + custcode + "&itemCode=" + intstockcode + "&dateFrom=" + dtfrom + "&dateTo=" + dateTo;
    string jSon = CallApi(url);
    List<Itempricehistory> orders = new JavaScriptSerializer().Deserialize<List<Itempricehistory>>(jSon);

    DataSet dt = new DataSet();
    List<Itempricehistory> converttolist = new List<Itempricehistory>();

    Type elementType = typeof(Itempricehistory);
    DataSet ds = new DataSet();
    DataTable t = new DataTable();
    ds.Tables.Add(t);
    //creating rows in the datatable to that in the list
    foreach (var propInfo in elementType.GetProperties())
    {
        Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
        t.Columns.Add(propInfo.Name, ColType);

    }
    //
    foreach (Itempricehistory item in orders)
    {
        DataRow row = t.NewRow();

        foreach (var propInfo in elementType.GetProperties())
        {
            row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
        }

        t.Rows.Add(row);
    }



  List<Itempricehistory> convertreturntolist = new List<Itempricehistory>();

  t.Columns.Add("DateStr");
  t.AcceptChanges();
   // t.WriteXmlSchema(@"C:\Temp\Amit.xml");
  foreach (DataRow dr in t.Rows)
  {
      DateTime dDate;
      try
      {

          dDate = Convert.ToDateTime(dr["Date"]);
          dr["DateStr"] = dDate.ToString("yyyy-MM");
      }
      catch (Exception)
      {

          throw;
      }
  }


  t.AcceptChanges();

  t = t.AsEnumerable().GroupBy(r => r.Field<string>("DateStr")).Select(g => g.FirstOrDefault()).CopyToDataTable();



 //query to sort by itemname itemcode




  DataTable dtnew = new DataTable();
  DataView view = t.DefaultView;
  view.Sort = "DateStr DESC";
  dtnew = view.ToTable();



    List<Itempricehistory> data = new List<Itempricehistory>();
    foreach (DataRow row in dtnew.Rows)
    {
        data.Add(new Itempricehistory
        {

            CustomerId = row["CustomerId"].ToString(),
            CustomerName = row["CustomerName"].ToString(),
            CustomerOrderNumber = row["CustomerOrderNumber"].ToString(),
            CustomerTaxZone = row["CustomerTaxZone"].ToString(),
            Date = row["DateStr"].ToString(),
            DiscAmt = row["DiscAmt"].ToString(),
            InventoryId = row["InventoryId"].ToString(),
            ItemDescription = row["ItemDescription"].ToString(),
            LineTotal = row["LineTotal"].ToString(),
            OpenQty = row["OpenQty"].ToString(),
            OrderNbr = row["OrderNbr"].ToString(),
            OrderTotal = row["OrderTotal"].ToString(),
            QtyOnShipments = row["QtyOnShipments"].ToString(),
            Quantity = row["Quantity"].ToString(),
            TaxCategory = row["TaxCategory"].ToString(),
            TaxId = row["TaxId"].ToString(),
            TaxRate = row["TaxRate"].ToString(),
            UnitPrice = row["UnitPrice"].ToString(),
            UOM = row["UOM"].ToString(),
            StockCode = row["StockCode"].ToString()
        });
    }
    return data.AsQueryable();
}
Posted
Updated 22-Oct-15 21:40pm
v2
Comments
Sreekanth Mothukuru 23-Oct-15 4:01am    
You need to convert your JavaScript method to accept strings like param within double quotes(") something like this:

onclick='OpenItemhistoryPopup("'#=StockCode #'")'
Sinisa Hajnal 23-Oct-15 7:51am    
I cannot help with the event, but spotted your
int intstockcode = Convert.ToInt32(stockcode);
which will fail (throw an exception) if the stockcode ISN'T a number. Use Int.TryParse or check that the value is a number before converting it.
Amit Karyekar 28-Oct-15 5:38am    
Hi
Well tat was the bit which worked ,the rest was fine.
So the solution was to just remove the line for integer conversion as I was passing the string and converting it to int.
Sinisa Hajnal 28-Oct-15 9:28am    
Yes, it would work as long as your strings are integers...but $100 or abc would fail. That's why I advised fail safe mechanism. Sorry if it wasn't clear.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900