简体   繁体   中英

How to pass data to jquery in view from controller

I've a Viewbag in my controller. And i want to reach it from jquery code in view. Is it possible? I want to check my customer's money about if it is enough for buy the product. If they don't have money enough i want to show them a sweet alert. Is it possible and if it is how can i do it?

That's my [GET] controller;

 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);
    }

That's my [POST] controller;

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);
    }

And that's my view

   @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>
        }

add this class:

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

then in controller returned Json value:

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,
            });
    }

and in script:

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;
}

You can not transfer the program to another view with an ajax request, but you have to go back to the desired page with javascript depending on the situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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