я могу использовать один метод контроллера в js? - PullRequest
1 голос
/ 03 апреля 2020

Мне нужна помощь, чтобы получить решение вопроса. Дело в следующем:

Мы работаем над групповым проектом с технологиями asp. net, c #, javascript, html и бритвой.

Структура проектов в рамках решения выглядит следующим образом:

1.POJO-сущности: где расположены модели.

2.DataAccess: он разделен на три папки: 1. Crud ( где классы, которые содержат «грубую фабрику» каждого Pojo, 2. Dao (найдите соединение с базой данных, в данном случае SQL Server) и, наконец, Mapper

3.CoreApi, где менеджеры каждой скважины.

4.WebApi, где контроллеры каждой скважины.

5.WepApp, где находится пользовательский интерфейс (cshtmls) и javascripts. Теперь я должен реализовать виртуальный кошелек, который можно пополнить через PayPal, и у меня есть метод, который получает цену и описание платежа, сейчас он «сожжен», но его можно параметризировать. Я хочу знать, могу ли я взять значение CtrlInput и положить его в HTML-атрибуты моего ActionLi nk.

Идея может удалить @ Html .ActionLink и оставить функциональность в «Обновлении», но я не знаю, как отправить параметры из представления JS в контроллер PayPal .

Это код javascript для представления кошелька:

function vMonedero() {

    //this.tblMonederoId = 'tblMonedero';
    this.service = 'monedero';
    this.ctrlActions = new ControlActions();
    this.columns = "IdUsuario, IdMonedero, Monto";
    this.paypal = new PaymentWithPayPal();

    this.RetrieveAll = function () {
        this.ctrlActions.FillTable(this.service, this.tblMonedero, false);
    }


    this.Create = function () {
        var monederoData = {};
        monederoData = this.ctrlActions.GetDataForm('frmEdition');
        if (monederoData["Monto"] == "") {
            this.ctrlActions.ShowMessage('E', "Favor ingresar el nuevo valor");
        }
        else if (isNaN(monederoData["Monto"])) {
            this.ctrlActions.ShowMessage('E', "Favor ingresar un valor numérico");
        }
        else {
            this.ctrlActions.PostToAPI(this.service, monederoData);

        }
    }

    this.Update = function () {

        var monederoData = {};
        monederoData = this.ctrlActions.GetDataForm('frmEdition');
        price = monederoData["Monto"];
        paypal.PaymentWithPayPal(price, "Recarga de monedero");
        //Hace el post al create
        this.ctrlActions.PutToAPI(this.service, monederoData);
        //Refresca la tabla

    }
    this.Delete = function () {

        var monederoData = {};
        monederoData = this.ctrlActions.GetDataForm('frmEdition');
        //Hace el post al create
        this.ctrlActions.DeleteToAPI(this.service, monederoData);
        //Refresca la tabla

    }

    this.BindFields = function (data) {
        this.ctrlActions.BindFields('frmEdition', data);
    }
}

//ON DOCUMENT READY
$(document).ready(function () {

    var vmonedero = new vMonedero();
    //vmonedero.RetrieveAll();

});

Это код вида:

@using WebApp.Helpers;

<script src="~/Scripts/Views/vMonedero.js"></script>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="card border-secondary" style="margin-top: 50px;">
    <div class="card-header">
        <div class="row pull-right">
            <div class="col-md-8">Monedero</div>
            <div class="col-md-4">
                @Html.CtrlButton(viewName: "vMonedero", id: "btnCreate", label: "Crear", onClickFunction: "Create", buttonType: "success")
                @Html.CtrlButton(viewName: "vMonedero", id: "btnUpdate", label: "Recargar", onClickFunction: "Update", buttonType: "info")

            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-lg-6">
                <div class="bs-component">
                    <form id="frmEdition">
                        @Html.CtrlInput(id: "txtIdUsuario", type: "text", label: "N° de identificación", columnDataName: "IdUsuario")
                        @Html.CtrlInput(id: "txtIdMonedero", type: "text", label: "N° de monedero", columnDataName: "IdMonedero")
                        @Html.CtrlInput(id: "txtIdMonto", type: "text", label: "Monto", columnDataName: "Monto")
                        @* @Html.CtrlDropDown(id: "drpGender", label: "Gender", listId: "LST_GENERO")*@
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@*<script>
    $('#price').click(function () {
        var monederoData = {};
        ctrlActions = new ControlActions();
        ctrlActions.GetDataForm('frmEdition');
        monederoData["Monto"] = price;
        return price;
    });
</script>*@

Код контроллера Paypal:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PaymentPayPal.Models;
using PayPal.Api;

namespace WebApp.Controllers
{
    public class PayPalController : Controller
    {
        // GET: PayPal
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult PaymentWithPaypal(string price, string product)
        {
            //getting the apiContext as earlier
            APIContext apiContext = ConfigurationPayPal.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {

                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority +
                                "/Paypal/PaymentWithPayPal?";

                    var guid = Convert.ToString((new Random()).Next(100000));

                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid, price, product);

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            paypalRedirectUrl = lnk.href;
                        }
                    }
                    Session.Add(guid, createdPayment.id);
                    Console.WriteLine(createdPayment.id);
                    return Redirect(paypalRedirectUrl);
                }
                else
                {
                    var guid = Request.Params["guid"];
                    Console.WriteLine("Session:" + Session[guid] as string);
                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return View("FailureView");
                    }
                }
            }
            catch (Exception ex)
            { 
                return View("FailureView");
            }

            return View("SuccessView");
        }

        private PayPal.Api.Payment payment;

        private Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
        {
            var paymentExecution = new PaymentExecution() { payer_id = payerId };
            this.payment = new Payment() { id = paymentId };
            return this.payment.Execute(apiContext, paymentExecution);
        }

        private Payment CreatePayment(APIContext apiContext, string redirectUrl, string price, string product)
        {

            var itemList = new ItemList() { items = new List<Item>() };

            itemList.items.Add(new Item()
            {
                name = product,
                currency = "USD",
                price = price,
                quantity = "1",
                sku = "sku"
            });

            var payer = new Payer() { payment_method = "paypal" };

            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                tax = "1",
                shipping = "1",
                subtotal = price
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "USD",
                total = "" + (int.Parse(price) + 1 + 1), // Total must be equal to sum of shipping, tax and subtotal.
                details = details
            };

            var transactionList = new List<Transaction>();

            transactionList.Add(new Transaction()
            {
                description = "Transaction description.",
                invoice_number = Convert.ToString((new Random()).Next(100000)),
                amount = amount,
                item_list = itemList
            });

            this.payment = new Payment()
            {
                intent = "sale",
                payer = payer,
                transactions = transactionList,
                redirect_urls = redirUrls
            };
            // Create a payment using a APIContext
            return this.payment.Create(apiContext);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...