【问题标题】:How to pass data to jquery in view from controller如何从控制器将数据传递给jquery
【发布时间】:2021-04-27 20:09:37
【问题描述】:

我的控制器中有一个 Viewbag。我想从jquery代码中看到它。可能吗? 我想检查客户的钱是否足以购买产品。如果他们没有足够的钱,我想向他们展示一个甜蜜的警报。有可能吗?如果可以,我该怎么做?

那是我的 [GET] 控制器;

 public ActionResult inspect(string id, int page = 1)
    {
        if (id == null)
        {
            return RedirectToAction("account", "product");
        }
        ViewBag.href = id;
        ViewBag.user = Session["MAIL"];
        var valuehrefid = db.TBLPRODUCT.Where(x => x.href == id).Select(y => y.ID).FirstOrDefault();
        var accounts = db.TBLACCOUNT.Where(x => x.PRODUCT == valuehrefid && x.status == true).ToList().ToPagedList(page, 10);
        return View(accounts);
    }

那是我的 [POST] 控制器;

public ActionResult buyaccount(int id)
    {
        var mail = (string)Session["MAIL"];
        var userid = db.TBLUSER.Where(x => x.MAIL == mail).Select(y => y.ID).FirstOrDefault();
        var price = db.TBLACCOUNT.Where(x => x.ID == id).Select(y => y.PRICE).FirstOrDefault();
        var user = db.TBLUSER.Find(userid);
        if (user == null || mail == null)
        {
            ViewBag.alert = "usernull";
            return RedirectToAction("login", "home");
        }
        var href = db.TBLACCOUNT.Where(x => x.ID == id).Select(y => y.TBLPRODUCT.href).FirstOrDefault();
        var customercash = user.CASH;
        if (customercash >= price)
        {
            user.CASH -= price;
            var value = db.TBLACCOUNT.Find(id);
            value.status = false;
            var product = db.TBLACCOUNT.Where(x => x.ID == id).Select(y => y.TBLPRODUCT.ID).FirstOrDefault();
            var productd = db.TBLPRODUCT.Find(urun);
            product.STOCK -= 1;
            var date = DateTime.Parse(DateTime.Now.ToShortDateString());
            TBLSALEACTION p = new TBLSALEACTION();
            p.CUSTOMER = userid;
            p.ACCOUNT = id;
            p.PRODUCT = product;
            p.DATE = date;
            p.PRICE = price;
            db.TBLSALEACTION.Add(p);
            db.SaveChanges();
            ViewBag.Uyari = "successful";
        }
        else
        {
            ViewBag.Uyari = "Customer's money is not enough to buy this.";
            int sayfa = 1;
            var valuehrefid = db.TBLPRODUCT.Where(x => x.href == href).Select(y => y.ID).FirstOrDefault();
            var accounts = db.TBLACCOUNT.Where(x => x.PRODUCT == valuehrefid && x.status == true).ToList().ToPagedList(sayfa, 10);
            return View("inspect", model: hesaplar);
        }
        return View("~/Views/accounts/inspect/" + href + ".cshtml", href);
    }

这就是我的观点

   @if (Session["MAIL"] != null)
        {
    <script>
                $('#TBLACCOUNT').on("click", ".btnBuy", function () {
                    var btn = $(this);
                    Swal.fire({
                        title: 'Warning',
                        text: "Are you sure to buy this?",
                        type: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#3085d6',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Yes',
                        cancelButtonText: 'No'
                    }).then((result) => {
                        if (result.value) {
                            var id = btn.data("id");
                            $.ajax({
                                type: "POST",
                                url: "/accounts/buyaccount/" + id,
                                success: function (s) {
                                    if (s) {
                                btn.parent().parent().remove();
                                Swal.fire(
                                    'Information ',
                                    'You have successfully purchased!',
                                    'success'
                                );
                                    } else {
                                        Swal.fire({
                                            type: 'error',
                                            title: 'Error.',
                                            text: 'You dont have enough money.',
                                            confirmButtonText: 'Close'
                                        });
                                    }
                                }
                            });
                        }
                    });
                });
    </script>
        }

【问题讨论】:

    标签: c# jquery asp.net-mvc model-view-controller


    【解决方案1】:

    添加这个类:

    public class JsonData
    {
        public string HtmlUrl{ get; set; }
        public string HtmlBody { get; set; }
        public bool Success { get; set; }
    }
    

    然后在控制器中返回Json值:

    public ActionResult buyaccount(int id)
        {
            var mail = (string)Session["MAIL"];
            var userid = db.TBLUSER.Where(x => x.MAIL == mail).Select(y => y.ID).FirstOrDefault();
            var price = db.TBLACCOUNT.Where(x => x.ID == id).Select(y => y.PRICE).FirstOrDefault();
            var user = db.TBLUSER.Find(userid);
            if (user == null || mail == null)
            {
                 return Json(new JsonData()
                {
                    HtmlUrl = "/home/login",
                    HtmlBody = "usernull",
                    Success = false,
                });
            }
            var href = db.TBLACCOUNT.Where(x => x.ID == id).Select(y => y.TBLPRODUCT.href).FirstOrDefault();
            var customercash = user.CASH;
            if (customercash >= price)
            {
                user.CASH -= price;
                var value = db.TBLACCOUNT.Find(id);
                value.status = false;
                var product = db.TBLACCOUNT.Where(x => x.ID == id).Select(y => y.TBLPRODUCT.ID).FirstOrDefault();
                var productd = db.TBLPRODUCT.Find(urun);
                product.STOCK -= 1;
                var date = DateTime.Parse(DateTime.Now.ToShortDateString());
                TBLSALEACTION p = new TBLSALEACTION();
                p.CUSTOMER = userid;
                p.ACCOUNT = id;
                p.PRODUCT = product;
                p.DATE = date;
                p.PRICE = price;
                db.TBLSALEACTION.Add(p);
                db.SaveChanges();
            }
            else
            {
                
                int sayfa = 1;
                var valuehrefid = db.TBLPRODUCT.Where(x => x.href == href).Select(y => y.ID).FirstOrDefault();
                var accounts = db.TBLACCOUNT.Where(x => x.PRODUCT == valuehrefid && x.status == true).ToList().ToPagedList(sayfa, 10);
                return Json(new JsonData()
                {
                    HtmlUrl = "/accounts/inspect/hesaplar",
                    HtmlBody = "Customer's money is not enough to buy this.",
                    Success = false,
                });
            }
            
             return Json(new JsonData()
                {
                    HtmlUrl = "/accounts/inspect/href",
                    HtmlBody = "successful",
                    Success = true,
                });
        }
    

    在脚本中:

    if (s.Success) {
            btn.parent().parent().remove();
            Swal.fire(
                  'Information ',
                  'You have successfully purchased!',
                  'success'
               );
               window.location.href = s.HtmlUrl;
    } else {
            Swal.fire({
            type: 'error',
            title: 'Error.',
            text: s.MsgBody,
            confirmButtonText: 'Close'
        });
        window.location.href = s.HtmlUrl;
    }
    

    您不能通过ajax请求将程序转移到另一个视图,但您必须根据情况使用javascript返回所需的页面。

    【讨论】:

    • 谢谢,但可能我做不到。 :S 对不起,我是初学者。我也像您发送的那样更新了我的控制器。但它不会“购买帐户”行动。我如何将其重定向到带有 id 而没有 ajax 的 buyaccount 操作?这就是我的观点(就像你发送的那样); prnt.sc/xipfqq 我也更新了我的控制器,就像你发送的一样。我还创建了一个类。
    • 好的,我编辑了一些东西,它工作正常,但是当客户没有足够的钱购买产品时,即使如此甜蜜的警报也显示成功。我在控制器上有一个 viewbag。当客户没有钱时:Viewbag.Alert = "客户的钱不够买这个。";当客户有钱购买产品时:Viewbag.Alert = "successful";如何将它们传递给脚本中的视图?
    • 我刚刚修改了它。 jsonData 类可以返回三个值,它有两个字符串值,你可以定义任意多的变量。
    • 谢谢,你救了我的命 :) 祝你有美好的一天
    猜你喜欢
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2020-05-29
    • 2020-11-09
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    相关资源
    最近更新 更多