加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在DropDownFor值更改时更改EditorFor的值

发布时间:2020-12-15 23:29:42 所属栏目:百科 来源:网络整理
导读:我正在尝试建立一个在线银行网站(用于学习ASP.NET MVC).我有一个班级帐户 class Account{int account_id;String account_number;decimal balance;} 我有一个交易模型. public class MakeTransactionModel { [Required] public String AccountFrom { get; set
我正在尝试建立一个在线银行网站(用于学习ASP.NET MVC).我有一个班级帐户

class Account
{
int account_id;
String account_number;
decimal balance;
}

我有一个交易模型.

public class MakeTransactionModel
    {
        [Required]
        public String AccountFrom { get; set; }
        [Required]
        public String AccountTo { get; set; }

        public Decimal OrignalBalance { get; set; }
        [Required]
        public Decimal Amount { get; set; }
        [Required]
        public String TransactionFor { get; set; }
    }

然后在控制器中,我将帐户放在ViewBag中.

ViewBag.account_from = new SelectList(db.Accounts,"account_id","account_number");

在View中,我创建了一个显示所有帐户的下拉菜单

@Html.DropDownListFor(u => u.AccountFrom,(SelectList)ViewBag.account_from,htmlAttributes: new { @class = "form-control",@id = "AccountFrom",onchange=@"
                    @Model.OrignalBalance = 1000; // I tried this but did not work
                " })

现在,我试图在EditorFor中显示所选帐户的余额

@Html.EditorFor(model => model.OrignalBalance,new { htmlAttributes = new { @id="OrignalBalance",@class = "form-control",disabled = "disabled",@readonly = "readonly" } })

我在ViewBag中拥有所有账户,并且我显示下拉账户号码(这些账户中也有余额).我试图在DropDownFor值更改时更改EditorFor的值但仍无法执行此操作.我尝试使用jquery做到这一点,但我不知道我可以在jquery中使用LINQ

我的jquery代码是

<script type="text/javascript">

        $(document).ready(function () {
            $(function () {
                $('#AccountFrom').change(function () {
                    var selectedValue = $('#AccountFrom').text();
                    $('#OrignalBalance').val(@{new BankEntities().Accounts.SingleOrDefault(acc => acc.account_number == $('#AccountFrom').text())});   // I am trying to do this
                });
            });
        }
    )
    </script>

如果我找到一个很好的解决方案,那将是很好的,所以我可以在更改事件上更新EditorFor.

谢谢.

解决方法

您应该进行ajax呼叫并传递帐号并从服务器获取金额.

$(function()
{
    $('#AccountFrom').change(function() {
    var accountId= $('#AccountFrom').val();
    var url="@Url.Action("Balance","Account")";
       $.post(url+"?accountNumber="+accountId,function(response){
          if(response.Status==="success")
          {
            $("#OrignalBalance").val(response.Balance);
          }
          else
          {
             alert("Invalid Account");
          }
       });
    });
});

假设您有一个动作方法来返回余额

[HttpPost]
public ActionResult Balance(string accountNumber)
{
   //Of course you want to authorize the call
   var db=new BankEntities();
   var a= db.Accounts.FirstOrDefault(x=> x.account_number ==accountNumber);
   if(a!=null)
   {
      return Json( new { Status="success",Balance=a.Balance });
   }
   else
   {
     return Json( new { Status="error"});
   }
}

如果您不想制作动作方法和ajax方式,您可以做的是,创建您的帐号和余额的字典,并将其作为视图模型的一部分并在剃刀视图中传递,将其设置为js对象,在更改事件中,您可以查询js字典以获取值.

另外,我建议不要使用ViewBag在操作方法和视图之间传输数据以呈现下拉列表.您应该添加一个强类型属性来处理它.

因此,让我们为您的视图模型添加一些新属性.

public class MakeTransactionModel
{
   // Your other existing properties here

   public Dictionary<string,decimal> AccountBalances { set; get; }   

   // These 2 properties are for rendering the dropdown.
   public int FromAccountId { set; get; }
   public List<SelectListItem> FromAccounts { set; get; }  
}

在您的GET操作中,使用帐号和相应的余额值填写此属性.

public ActionResult Transfer()
{
  var vm = new MakeTransactionModel();
  vm.AccountBalances = new Dictionary<string,decimal>();
  // Hard coded for demo. You may read it from your db tables.
  vm.AccountBalances.Add("CHECKING0001",3450.50M);
  vm.AccountBalances.Add("SAVINGS0001",4450.50M);

   //load the data for accounts.pls change to get from db
   vm.FromAccounts = new List<SelectListItem>
   {
       new SelectListItem { Value="CHECKING0001",Text="Checking" },new SelectListItem { Value="SAVINGS0001",Text="Saving" }
   };

  // to do : Load other properties also
  return View(vm);
}

在剃须刀视图中,序列化此属性并设置为js对象.

@model MakeTransactionModel
@using(Html.BeginForm())
{
  @Html.DropDownListFor(s=>s.FromAccountId,Model.FromAccounts,"Select")

  @Html.EditorFor(model => model.OrignalBalance,new { @id="OrignalBalance",@readonly = "readonly" } )
  <input type="submit" />
}
@section Scripts
{
<script>   
var balanceDict = @Html.Raw(Newtonsoft.Json.JsonConvert
                               .SerializeObject(Model.AccountBalances));

$(function () {

    $('#FromAccountId').change(function() {
        var accountId= $('#AccountFrom').val();
        var v = balanceDict[accountId];
        $("#OrignalBalance").val(v);
    });   

});
</script>
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读