无需刷新页面即可更新数据库调用

时间:2015-10-11 01:51:18

标签: c# jquery ajax asp.net-mvc-5

向用户显示图像列表(宝藏),用户将在此处选择将存储在Learner_treauser表中的单个图像:

List<The_Factory_Chante.Models.Treasure> tresh;

using (The_Factory_Chante.Models.The_FactoryDBContext db2 = new The_Factory_Chante.Models.The_FactoryDBContext())
{

    string imageSource = "";

    tresh = db2.Treasures.ToList();

    foreach (var item in tresh)
    {
        if (item.itemImage != null)
        {
            string imageBase = Convert.ToBase64String(item.itemImage);
            imageSource = string.Format("data:image/gif;base64,{0}", imageBase);
        }

        <img id="@item.treasureID" src="@imageSource" onclick="return MakeSure(@item.treasureID)" />
    }
}

选择图像时调用的函数。在此函数中,图像将被发送到Web服务方法以保存到数据库,并重新加载页面以进行更新:

function MakeSure(treshID) {

    var id = treshID
    $.ajax({
        url: "../../WebService.asmx/MakeSure",
        data: "{ 'id': '" + id + "'}",
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }

    });
    window.location.reload();
};

然而,就用户而言,这并不是很愉快。更好的方法是更新而不刷新页面。

以下是Webservice方法,它接收所选的图像ID并将其存储在Learner_Treasure表中。

public void MakeSure(int id)
{
   using (The_FactoryDBContext db = new The_FactoryDBContext())
   {
       Learner_Treasure learnTreasure = new Learner_Treasure();

       learnTreasure.dateCompleted = DateTime.Today;
       learnTreasure.learnerID = UserInfo.ID;
       learnTreasure.treasureID = id;

       db.Learner_Treasure.Add(learnTreasure);
       db.SaveChanges();

   }

调用Learner_Treasure表的代码。

List<The_Factory_Chante.Models.Learner_Treasure> lern;
using (The_Factory_Chante.Models.The_FactoryDBContext db2 = new The_Factory_Chante.Models.The_FactoryDBContext())
{

    string imageSource = "";
    lern = db2.Learner_Treasure.ToList();
    if (lern != null)
    {
        foreach (var item in lern)
        {
            if (item.learnerID == UserInfo.ID)
            {
                byte[] bytes = db2.Treasures.FirstOrDefault(au => au.treasureID == item.treasureID).itemImage;
                string imageBase = Convert.ToBase64String(bytes);
                imageSource = string.Format("data:image/gif;base64,{0}", imageBase);
                <img id="@item.treasureID" src="@imageSource"/>
            }
        }

此代码将向用户显示他们选择的所有图像,但如果我带走window.location.reload();,则此代码仅在页面重新加载时更新。这意味着用户在选择图像后不会立即看到所选图像。

我想要做的是更新调用Learner_Table的代码而不刷新页面。

5 个答案:

答案 0 :(得分:2)

还有另一种解决此问题的方法,您可以使用SignalR库。

这是您需要做的事情:

查看

// Include the SignalR Script
<script src="~/Scripts/jquery.signalR-2.2.0.js"></script>

// Provide a dynamic proxy for SignalR
<script src="~/signalr/hubs"></script>

// Define hub connection(see below)
var hub = $.connection.yourHub;

// This is what the Hub will call (Clients.All.getImage(imageSource);)
hub.client.getImage = function (img) {
    var image = '<img id="' + img.treasureId + '" src="data:image/jpg;base64,' + img.image + '"';
    $(image).appendTo("body");
};

// Start the connection to the hub
// Once we have a connection then call the getLearnerTreasureItem on the Hub
$.connection.hub.start().done(function () {
    var id = // whatever
    hub.server.getLearnerTreasureItem(id);
};

<强>集线器

public class YourHub : Hub
{

    public void GetLearnerTreasureItem()
    {
        // All your code
        List<The_Factory_Chante.Models.Learner_Treasure> lern;
        using (The_Factory_Chante.Models.The_FactoryDBContext db2 = new The_Factory_Chante.Models.The_FactoryDBContext())
        {

         string imageSource = "";
         lern = db2.Learner_Treasure.ToList();
         if (lern != null)
         {
           foreach (var item in lern)
           {
             if (item.learnerID == UserInfo.ID)
             {
               byte[] bytes = db2.Treasures.FirstOrDefault(au => au.treasureID == item.treasureID).itemImage;
              string imageBase = Convert.ToBase64String(bytes);
              imageSource = string.Format("data:image/gif;base64,{0}", imageBase);
            }
        }

        // This will now call the getImage function on your view.
        Clients.All.getImage(imageSource);
    }
}

有关dynamic proxy

的信息

答案 1 :(得分:0)

您的问题是onclick事件处理程序:

<img id="@item.treasureID" src="@imageSource" onclick="return MakeSure(@item.treasureID)" />

MakeSure()功能中,您不会返回任何内容。因此,您有两个选项,更改MakeSure()函数以在结尾处返回false,或者更改onclick事件以在图像元素中的第一个函数调用后返回false,如onclick="MakeSure(@item.TreasureID); return false;"

此外,您必须从window.location.reload();功能中删除MakeSure()

旁注,似乎你在你的视图中混淆了你的DbContext,如果是这样,这是非常糟糕的做法。您应该将数据访问放在某种服务层之后,该服务层充当视图和数据之间的中介。

更新

好几次读完你的问题后,我理解你的问题了 问题是你的第二段代码。

List<The_Factory_Chante.Models.Learner_Treasure> lern;
using (The_Factory_Chante.Models.The_FactoryDBContext db2 = new The_Factory_Chante.Models.The_FactoryDBContext())
{

    string imageSource = "";
    lern = db2.Learner_Treasure.ToList();
    if (lern != null)
    {
        foreach (var item in lern)
        {
            if (item.learnerID == UserInfo.ID)
            {
                byte[] bytes = db2.Treasures.FirstOrDefault(au => au.treasureID == item.treasureID).itemImage;
                string imageBase = Convert.ToBase64String(bytes);
                imageSource = string.Format("data:image/gif;base64,{0}", imageBase);
                <img id="@item.treasureID" src="@imageSource"/>
            }
        }
    }
}

这将调用DB并获取用于在视图上输出的Learner_Treasure个对象的列表。每个页面请求都会执行一次服务器端代码,这正是发生的事情。 如果没有向服务器发出请求,它将不会异步更新。

您需要实现ajax请求以将最新的Learner_Treasure列表拉入视图。这再次归结为我给出的第一个侧面注释,原因是因为您正在将dbcontext与您的视图混合并期望它在动态更新。如果您实现了一个使用数据(控制器)为您的视图提供服务的层,您可以异步调用它并让页面更新而不重新加载。

例如,您可以在控制器中编写一个调用来获取json中的单个LearnerTreasure项。

[HttpGet]
public ActionResult GetLearnerTreasureItem(int Id)
{
    using (The_Factory_Chante.Models.The_FactoryDBContext db2 = new The_Factory_Chante.Models.The_FactoryDBContext()) {
        learnerTreasureItem = db2.Learner_Treasure.FirstOrDefault(x => x.Id == Id);
        return Json(new { image = Convert.ToBase64String(learnerTreasureItem.itemImage), treasureId = learnerTreasureItem.TreasureID }, JsonRequestBehavior.AllowGet);
    }
}

然后在您的视图中使用ajax调用它,就像您使用更新一样。

$.ajax({
    cache: false,
    type: "GET",
    url: '/YOURCONTROLLERNAME/GetLearnerTreasureItem?id=1',
    contentType: 'application/json',
    dataType: "json",
    success: function (data) {
        //build image element
        var image = '<img id="' + data.treasureId + '" src="data:image/jpg;base64,' + data.image + '"';

        //add the image to where you need it.
        $(image).appendTo("body");
    },
    error: function (xhr) {
       alert("Error occurred while loading the image.");
    }
});

我希望这会有所帮助。

答案 2 :(得分:0)

我接近这个的方法是为需要刷新的代码制作部分视图

<div style="float: left; width: 500px">
                <h4>Search Your Countries or City</h4>
                <input class="countries-cities typeahead" type="text" placeholder="Countries And Cities">
            </div>

然后在成功的$ .ajax后我刷新它

PLATFORM VERSION INFO
    Windows             : 6.2.9200.0 (Win32NT)
    Common Language Runtime     : 4.0.30319.42000
    System.Deployment.dll       : 4.6.81.0 built by: NETFXREL2
    clr.dll             : 4.6.96.0 built by: NETFXREL2STAGE
    dfdll.dll           : 4.6.81.0 built by: NETFXREL2
    dfshim.dll          : 6.3.9600.16384 (winblue_rtm.130821-1623)

SOURCES
    Deployment url          : http://github-windows.s3.amazonaws.com/GitHub.application
                        Server      : AmazonS3
    Application url         : http://github-windows.s3.amazonaws.com/Application%20Files/GitHub_3_0_6_4/GitHub.exe.manifest
                        Server      : AmazonS3

IDENTITIES
    Deployment Identity     : GitHub.application, Version=3.0.6.4, Culture=neutral, PublicKeyToken=317444273a93ac29, processorArchitecture=x86

APPLICATION SUMMARY
    * Installable application.
    * Trust url parameter is set.
ERROR SUMMARY
    Below is a summary of the errors, details of these errors are listed later in the log.
    * Activation of http://github-windows.s3.amazonaws.com/GitHub.application resulted in exception. Following failure messages were detected:
        + Specified cast is not valid.

COMPONENT STORE TRANSACTION FAILURE SUMMARY
    No transaction error was detected.

WARNINGS
    There were no warnings during this operation.

OPERATION PROGRESS STATUS
    * [13-10-2015 11:43:54] : Activation of http://github-windows.s3.amazonaws.com/GitHub.application has started.
    * [13-10-2015 11:43:55] : Processing of deployment manifest has successfully completed.
    * [13-10-2015 11:43:55] : Installation of the application has started.

ERROR DETAILS
    Following errors were detected during this operation.
    * [13-10-2015 11:43:57] System.InvalidCastException
        - Specified cast is not valid.
        - Source: System.Deployment
        - Stack trace:
            at System.Deployment.Application.DownloadManager.VerifyRequestedPrivilegesSupport(String requestedExecutionLevel)
            at System.Deployment.Application.DownloadManager.DownloadApplicationManifest(AssemblyManifest deploymentManifest, String targetDir, Uri deploymentUri, IDownloadNotification notification, DownloadOptions options, Uri& appSourceUri, String& appManifestPath)
            at System.Deployment.Application.ApplicationActivator.DownloadApplication(SubscriptionState subState, ActivationDescription actDesc, Int64 transactionId, TempDirectory& downloadTemp)
            at System.Deployment.Application.ApplicationActivator.InstallApplication(SubscriptionState& subState, ActivationDescription actDesc)
            at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl)
            at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)

COMPONENT STORE TRANSACTION DETAILS
    No transaction information is available.

答案 3 :(得分:0)

更新宝藏图片列表

<img id="@item.treasureID" src="@imageSource" onclick="return MakeSure(this, @item.treasureID)" />

在MakeSure方法中读取该参数。我还假设在名为'ulLearnerTreasure'的ul中列出了Learner_Treasure图像。

function MakeSure(sender,treshID) {
          var id = treshID;
          var imgSrc = $(sender).attr("src");
                $.ajax({
                    url: "../../WebService.asmx/MakeSure",
                    data: "{ 'id': '" + id + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        var li = '<li><img id ="'+ treshID +'"src="'+ imgSrc  +'" /></li>';
                        $("#ulLearnerTreasure").append(li);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

                    }

                });

            };

答案 4 :(得分:0)

我会使用HtmlHelpers实现它,如下所示:(正如有人建议的那样,直接使用db代码不是一个好习惯,你需要改变它。)

public static class HTMLHelpers
{
    public static IHtmlString TreasureImages(this HtmlHelper helper, List<The_Factory_Chante.Models.Learner_Treasure> lern)
    {
        StringBuilder sb = new StringBuilder();
        using (The_Factory_Chante.Models.The_FactoryDBContext db2 = new The_Factory_Chante.Models.The_FactoryDBContext())
        {

            string imageSource = "";
            lern = db2.Learner_Treasure.ToList();
            if (lern != null)
            {
                foreach (var item in lern)
                {
                    if (item.learnerID == UserInfo.ID)
                    {
                        byte[] bytes = db2.Treasures.FirstOrDefault(au => au.treasureID == item.treasureID).itemImage;
                        string imageBase = Convert.ToBase64String(bytes);
                        imageSource = string.Format("data:image/gif;base64,{0}", imageBase);
                        sb.Append("<li><img id='@item.treasureID' src='@imageSource'/></li>");
                    }
                }
            }
        }
        return new HtmlString(sb.ToString());
    }
}

图片的占位符:

<ul id="TreaureImagesSection">
</ul>

在您的cshtml页面中,第一次或在您需要更新列表的时候使用此脚本加载列表

<script>
    $.ajax({
    cache: false,
    type: "GET",
    url: '/YOURCONTROLLER/TreasuresList',
    contentType: 'application/json; charset=utf-8',
    success: function (data) {  // the data returned is List<The_Factory_Chante.Models.Learner_Treasure>
        $("#TreaureImagesSection").html('@Html.TreasureImages(data)');
    },
    error: function (xhr) {
        alert("Error occurred while loading the image.");
    }
});
</script>