使用jQuery和不同的控制器/函数更新@Model

时间:2019-11-09 17:54:35

标签: jquery asp.net-mvc model

我将仅仅因为它有点复杂而尝试解释它: 我正在尝试创建一个区块链钱包,我使用AccountController成功加载了视图。那里有钱包余额,一切都很好。

但是有时我想转账(=更改钱包余额) 我的视图使用从AccountController(Account类)返回的@Model读取余额。

我的问题是更新@Model。从我所做的事情来看-到目前为止没有任何改变。

在张贴收件人地址和资金以转回服务器后,使用jQuery(按一个按钮)直接进入另一个控制器, 我需要将@Model返回到具有更新后余额的视图,该平衡将被立即调用到已读取它的HTML元素中。 在服务器中,我已经有具有相同详细信息的帐户实例。

这是我的代码:

HTML:

  <label id="ETH-Value">@Model.AccountBalance ETH</label>
  <table>
      .....
      <tr >
         <td style="">
         <input name="RecipientAmmountInput" type="number"  required="required" id="RecipientAmmountInput" placeholder="Enter Ammount" min="0" max=@Model.AccountBalance>
         </td>
         <td ">
            <a style="color:blue;" href="javascript:void(0);"  onclick="SendMoneyTransaction()" id="nextButton"><strong>Next></strong></a>
         </td>
       </tr>
  </table>

jQuery:

  function SendMoneyTransaction()
    { 
        var recipientAddress = $('#RecipientAddressInput').val();
        var tranferValueETH = $('#RecipientAmmountInput').val();
        .....
        var url = "/SendDepositETH/SendMoney";
        $.post(url, { AddressTo: recipientAddress, Amount: tranferValueETH }, function (data) 
        {
          //The post is working
            ...
         }) 

C#(服务器):

 ...
 public class SendDepositETHController : Controller
 {
 [HttpPost]
    public IActionResult SendMoney(String AddressTo, String Amount)
    {
        double amountToSend = Convert.ToDouble(Amount);
        Account transferFrom = AccountController.myAccount;
        transferFrom.AccountBalance = amountToSend;  //for example
        return View(transferFrom);
    }

  }
  ....

1 个答案:

答案 0 :(得分:0)

在控制器中,您可以:return transferFrom;并将IActionResult更改为Account。 在视图中,

 $.post(url, { AddressTo: recipientAddress, Amount: tranferValueETH }, function (data) 
        {
          //The post is working
          // Something like this
            $("#ETH-Value").val(data.AccountBalance);
         })