简体   繁体   English

ASP.NET MVC和WebAPI插入和检索带有数据库表的记录

[英]ASP.NET MVC and WebAPI inserting and retriveing records with database table

I am currently using ASP.NET to create a web page. 我目前正在使用ASP.NET创建网页。

I have a page at the location: myUrl/INVs/Transaction 我在以下位置有一个页面:myUrl / INVs / Transaction

From the user point of view: what I am actually doing now is to create a list of items in my page. 从用户的角度来看:我现在实际要做的是在页面中创建项目列表。 Then after I press save button. 然后,我按保存按钮。 The same page is refreshed to show the items I created just now. 刷新同一页面以显示我刚才创建的项目。

In my View after I press the save button, it executes the below javascript code: 按下保存按钮后,在我的视图中,它执行以下javascript代码:

 //some javascript code written here. 
 for (i = 0; i < rowCount; i++) {
   //some javascript code written here. 

   $.ajax({
          type: 'POST',
          data: { 'obj': newYTDTRNIObj },
          url: '/INVs/ProcessCreateYTDTRNIAsync',
          success: function (data) {
          console.log(data);


         }
         });

 }
 if (currentVoucherNumIsEmpty) {
    $.ajax({
           type: 'POST',
           data: { 'obj': newInvVouchObj },
           url: '/INVs/ProcessPatchTABVOUAsync',
           success: function (data) {

           if (currentPageTitle == "Inventory Receipt- Misc Receipt") {
                            location.href = currentUrl + "INVs/Transaction?tType=1&id=" + newInvVouchObj.PREFIX + newInvVouchObj.VOUCHNO;


           } else if (currentPageTitle == "Inventory Receipt- Return To Stock") {
                            location.href = currentUrl + "INVs/Transaction?tType=2&id=" + newInvVouchObj.PREFIX + newInvVouchObj.VOUCHNO;

           } else if (currentPageTitle == "Inventory Receipt- Production Receipt") {
                            location.href = currentUrl + "INVs/Transaction?tType=3&id=" + newInvVouchObj.PREFIX + newInvVouchObj.VOUCHNO;

           } else if (currentPageTitle == "Inventory Receipt- Purchase Receipt") {
                            location.href = currentUrl + "INVs/Transaction?tType=4&id=" + newInvVouchObj.PREFIX + newInvVouchObj.VOUCHNO;

           } else if (currentPageTitle == "Inventory Issue- Misc Issue") {
                            location.href = currentUrl + "INVs/Transaction?tType=5&id=" + newInvVouchObj.PREFIX + newInvVouchObj.VOUCHNO;

           } else if (currentPageTitle == "Inventory Issue- Production Issue") {
                            location.href = currentUrl + "INVs/Transaction?tType=6&id=" + newInvVouchObj.PREFIX + newInvVouchObj.VOUCHNO;

           }

           }
           }); 

 }

It sends data over to controller with two ajax calls. 它通过两个ajax调用将数据发送到控制器。 At the success function of the 2nd ajax call, it redirects back to the same view again just that this time it is with parameters. 在第二次ajax调用的成功功能处,它再次重定向回同一视图,只是这次是带有参数。

When the view is called with those parameters, it actually loads and show those records that are inserted into database by that c# function above: ProcessCreateYTDTRNIAsync 当使用这些参数调用视图时,它实际上会加载并显示由上述c#函数插入到数据库中的记录: ProcessCreateYTDTRNIAsync

Below is my c# code: 以下是我的C#代码:

[HttpPost]
public async Task<string> ProcessCreateYTDTRNIAsync(INV_YTDTRNIObj obj, bool edit = false, bool issue = false)
{
        // some c# code written here. 

        var postTask = createclient.PostAsJsonAsync<YTDTRNI>("api/INV_API/postYTDTRNI", newYTDRNI);
                postTask.Wait();

                var result = postTask.Result;
                if (result.IsSuccessStatusCode){
                }

                return "Record created";
}

[Route("api/INV_API/postYTDTRNI/")]
public async Task<string> PostYTDTRNIAsync(YTDTRNI ytdtrniObj)
{

        db.YTDTRNIs.Add(ytdtrniObj);
        await db.SaveChangesAsync();

        return "YTDTRNI object created";
}


[HttpPost]
public async Task<string> ProcessPatchTABVOUAsync(TABVOU obj)
{

        // some c# code written here. 

        HttpClient client = new HttpClient();
        var result = await client.SendAsync(request);
        if (result.IsSuccessStatusCode)
        {

        }
        return "Updated voucher number";


}

What I noticed is that: When I insert 2 records, there are situations where after my view is displayed then the second record is inserted into the database table. 我注意到的是:当我插入2条记录时,在某些情况下,显示我的视图后,第二条记录将插入数据库表中。 So my view only displays the first record that was inserted.It is an inconsistent behavior, at other times, the 2 records are inserted in to the database table and when the page is refreshed, it displays the 2 records. 所以我的视图仅显示插入的第一条记录,这是一个不一致的行为,有时将2条记录插入数据库表中,并在刷新页面时显示2条记录。

Did this happen because I did not wait for first ajax to finish before refreshing the page? 发生这种情况是因为在刷新页面之前我没有等待第一个ajax完成吗?

This is what's called Ajax Cacheing . 这就是所谓的Ajax缓存

Ajax will chache your result so unless the page is refreshed or the cacheing is disabled, you won't see the updated data in your view. Ajax将检查结果,因此除非刷新页面或禁用缓存,否则您将在视图中看不到更新的数据。

There are a couple things you could try, first it to set your Ajax cahce to false : 您可以尝试几种方法,首先将Ajax cahce设置为false

  $.ajax({
           type: 'POST',
           data: { 'obj': newInvVouchObj },
           url: '/INVs/ProcessPatchTABVOUAsync',
           cache: false,
           success: function (data) {

Or globally with ajaxSetup() : 或全局使用ajaxSetup()

$.ajaxSetup({ cache: false });

I made use of the method mentioned in another question 我利用了另一个问题中提到的方法

I create an array which will store all the promises for ajax request which inserts data into database. 我创建了一个数组,该数组将存储将数据插入数据库的ajax请求的所有promise。

Then I use $.when.apply(null, promises).done to make sure the ajax requests in the for loop are completed before refreshing the page. 然后,我使用$.when.apply(null, promises).done来确保在刷新页面之前,for循环中的ajax请求已完成。 This ensures that all the data are inserted into database before page is refreshed. 这样可以确保在刷新页面之前将所有数据插入数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM