Readdy Write  
0,00 €
Your View Money
Views: Count
Self 20% 0
Your Content 60% 0

Users by Links 0
u1*(Content+Views) 10% 0
Follow-Follower 0
s2*(Income) 5% 0

Count
Followers 0
Login Register as User

Beispiel zum Upload von Daten an eine ASP Core API mit jquery Ajax und Json

06.10.2021 (👁1916)

Example to upload data on javascript to asp mvc api

 

Das folgende Beispiel zeigt, wie man in einer Asp Core MVC Anwendung Daten zu einer API hochlädt.

Dabei wird in ASP Core im Controller eine API (POST) erstellt, und in der ASP View zur Laufzeit im Client per javascript und jquery.ajax die Api aufgerufen und Daten übergeben.

 

Die Daten werden zuvor mit JSON verpackt und können somit struckturiert in einer Klasse auf dem Server entgegen genommen werden

 

Javascript to upload Data

Javascript Asp View Code cshtml  

 

 

function api_add_values(param_SetIDs, param_SetValue) {

    //--------< api_add_values(xx) >--------

    //*convert to json items

    var setItems= JSON.stringify({

        setids: param_SetIDs, //setIDs,    //1,2,3

        setvalue: param_SetValue  //setValue //"2021-10-06

    });

 

    //--< send_to_api >--

    $.ajax({

        //< setup_send >

        url: '/api/apiDemo/Add_Date_To_Products/',

        contentType: "application/json",

        type: 'POST',

        data: setItems,

        //</ setup_send >

 

        success: function (data) {

            //--< success >--

            alert(data);

            //--</ success >--

        },

        error: function (request, message, error) {

            //--< error >--

            //handleException(request, message, error);

            alert(error);

            //--</ error >--

        }

    });

    //--</ send_to_api >--

    //--------</ api_add_values(xx) >--------

}

 

 

Javascript to get Input Values from DevExtreme Controls

 

function onClickButtonSet(xx) {

    //--------< onClickButtonSet(xx) >--------

    //< get Date >

    var ctlSetDate = $("#ctlSetDate").dxDateBox("instance");

    var valDateSet = ctlSetDate.option('value'); 

    //</ get Date >

 

    //< check >

    if (valDateSet == null) { alert("no date is entered"); return; }

    var dtISOSet = valDateSet.toISOString().split("T")[0];

    //</ check >

 

    //< get Grid >

    var dataGrid = $("#gridDataTable").dxDataGrid("instance");

    var selectedRowsData = dataGrid.getSelectedRowsData();

    //</ get Grid >

    //*check if selected

    if (selectedRowsData.length==0) { alert("no row is selected"); return; }

   

 

    //*get selected IDs

    var selectedIDs = "";

    //--< @Loop: selectedRows >--

    for (var iRow = 0; iRow < selectedRowsData.length; iRow++) {

        var IDProduct = selectedRowsData[iRow]["IDProduct"];

        selectedIDs = selectedIDs + ";" + IDProduct;

        //console.log(selectedRowsData[iRow]);

    }

    //--</ @Loop: selectedRows >--

    if (selectedIDs.length > 0) selectedIDs = selectedIDs.substring(1);

 

 

    //< call Api >

    api_add_values(selectedIDs, dtISOSet);

    //</ call Api >

    //--------</ onClickButtonSet(xx) >--------

}

 

Ein Bild, das Text enthält.

Automatisch generierte Beschreibung

 

Api to load Data

ASP MVC Controller, C#

        //*Upload Data

        public class Upload_Item

        {

            public string setids { get; set; }

            public string setvalue { get; set; }

        }

 

        [HttpPost("Add_Date_To_Products")]

        public ActionResult Add_Date_To_Products([FromBody] Upload_Item setItems)

        {

            //-------------< UpdateGridCell() >-------------

           

            string sResult = JsonConvert.SerializeObject(setItems);

 

            return Ok(sResult);

            //-------------</ UpdateGridCell() >-------------

        }

 

 

Ein Bild, das Text enthält.

Automatisch generierte Beschreibung

 

 

apiController

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using MyApp.Models;

using DevExtreme.AspNet.Data;

using DevExtreme.AspNet.Mvc;

using MyApp.Models.DBContext;

using MvcContrib.UI.DataList;

using System.Data;

using Newtonsoft.Json;

using Microsoft.EntityFrameworkCore;

 

namespace MyApp.Controllers.Api

{

 

    [Route("api/[controller]")]

    [ApiController]

    public class apiDemoController : ControllerBase

    {

        #region Controller Init

        private readonly ApplicationDbContext _dbContext;

        public apiDemoController(ApplicationDbContext dbContext)

        {

            //----< Init: Controller >----

            _dbContext = dbContext;

            //----</ Init: Controller >----

        }

        #endregion

 

       

 

        [HttpGet("getGridData")]

        public object getGridData(DataSourceLoadOptions loadOptions,  string filterGridParameters)

        {

            //-------------< getDataGrid() >-------------

           

            var dsProducts = from tblProducts in _dbContext.tbl_Products

                                orderby tblProducts.Product ascending

                                select tblProducts;

               

            var dsProductDates = from tblProductDates in _dbContext.tbl_ProductDates

                orderby tblProductDates.IDProduct, tblProductDates.Date_Product ascending

                select tblProductDates;

 

 

            //--< Get Linq.Query >--

            DataTable tblMonth = new DataTable();   

            //< define Columns >

            tblMonth.Columns.Add("IDProduct", typeof(int));

            tblMonth.Columns.Add("Product", typeof(String));

 

            DateTime dtFrom = DateTime.Today.AddDays(- DateTime.Today.Day +1 );

            DateTime dtTo= DateTime.Today.AddMonths(6);

            DateTime dtLoop = dtFrom;

            while (dtLoop <= dtTo)

            {

                tblMonth.Columns.Add(dtLoop.ToString("yyyy-MM-01"), typeof(String));

                dtLoop = dtLoop.AddMonths(1);

            }

            //</ define Columns >

 

            //----< @Loop:Products >----

            foreach (var Product in dsProducts)

            {

                //----< [ Product ]----

                DataRow row = tblMonth.Rows.Add();

                row["IDProduct"] = Product.IDProduct;

                row["Product"] = Product.Product;

 

                //*SubQuery: Current Dates of Row Product

                var qDatesByProduct = dsProductDates.Where(p => p.IDProduct == Product.IDProduct && p.Date_Product>= dtFrom && p.Date_Product<=dtTo)

                    .Select(d=>new { dtMonth=d.Date_Product}) ;

                //----< @Loop:Products >----

                foreach (var ProductDate in qDatesByProduct)

                {

                    //----< [ Product ]----

                    string sMonth01 = ProductDate.dtMonth.ToString("yyyy-MM-01");

                    if (row[sMonth01] is System.DBNull) {

                        row[sMonth01] = ProductDate.dtMonth.ToString("yyyy-MM-dd");

                    }

                    else

                    {

                        row[sMonth01] = row[sMonth01] + ", " + ProductDate.dtMonth.ToString("yyyy-MM-dd");

                    }

                    //----</ [ Product ]----

                }

                //----</ @Loop:Products >----

 

                //----</ [ Product ]----

            }

                //----</ @Loop:Products >----

 

 

            List<DataRow> dataList = tblMonth.Select().ToList();

            //----< fill Data_to_View >----

            //---< @Loop: Rows >---

 

 

            //----</ fill Data_to_View >----

            return  JsonConvert.SerializeObject(tblMonth) ;

            //-------------</ getDataGrid() >-------------

        }

 

        [HttpPut("UpdateGridCell")]

        public ActionResult UpdateGridCell([FromForm] Dictionary<string,string> cell)

        {

            //-------------< UpdateGridCell() >-------------

            var sKey = cell["key"]; //ID=A

            var sCell_Column_Value = cell["values"]; //{"..":".."}

 

            sCell_Column_Value = sCell_Column_Value.Substring(1,sCell_Column_Value.Length-2);  //"..":".."

            string[] arrCell_Column_Value = sCell_Column_Value.Split(':');

 

            string sColumn_Name = arrCell_Column_Value[0];       //"col: 2021-10-01"

            string sCell_Value = arrCell_Column_Value[1];        //"val: 2021-10-10;2021-10-20;"

            sCell_Value = sCell_Value.Replace("\"","");

            DateTime dtCell = DateTime.Parse(sCell_Value);

 

            int IDProduct = Convert.ToInt32(sKey);

 

            ProductDateModel productDate = _dbContext.tbl_ProductDates.SingleOrDefault(p => p.IDProduct == IDProduct && p.Date_Product==dtCell);

            if(productDate == null)

            {

                try

                {

                    //< new ProductDate >

                    ProductDateModel newProductDate = new ProductDateModel();

                    newProductDate.Date_Product = dtCell;

                    newProductDate.IDProduct = IDProduct;

                    _dbContext.tbl_ProductDates.Add(newProductDate);    //*add 1 record

                    //</ new ProductDate >

 

                    _dbContext.SaveChanges();       //*update all in table

 

                    //----< Save Data >----           

                    try

                    {

                        //_dbContext.Update(newProductDate);

                        _dbContext.SaveChanges();

                    }

                    catch (DbUpdateConcurrencyException)

                    {

                        return Content("Update Error");

                    }

                    //----</ Save Data >----

 

                    //else

                    //{

                    //    //< Add on Server >

                    //    _dbContext.tbl_Notes.Add(note);

                    //    _dbContext.SaveChanges();

                    //    IDNote = note.IDNote;

                    //    //</ Add on Server >

                    //}

                    //await _dbContext.SaveChangesAsync(true);

                }

                catch (DbUpdateConcurrencyException ex)

                {

                    return Content("Error in saving ID:" + IDProduct + " Date:" +  productDate.Date_Product + ".. " + ex.Message);

                }

 

            }

 

 

            return Ok();

            //-------------</ UpdateGridCell() >-------------

        }

 

 

 

        //*Upload Data

        public class Upload_Item

        {

            public string setids { get; set; }

            public string setvalue { get; set; }

        }

 

        [HttpPost("Add_Date_To_Products")]

        public ActionResult Add_Date_To_Products([FromBody] Upload_Item setItems)

        {

            //-------------< UpdateGridCell() >-------------

           

            string sResult = JsonConvert.SerializeObject(setItems);

 

            return Ok(sResult);

            //-------------</ UpdateGridCell() >-------------

        }

 

    }

}