初学MVC,今天做个简单的功能,就是输入BeginDate和EndDate,从后台计算后赋值给另外一个文本框Amount

界面很简单,方法也很简单,今天就使用jquery的post方法,先准备后台代码

        public JsonResult GetAmount(string date1, string date2)
        {
            DateTime begin = DateTime.MinValue;
            DateTime end = DateTime.MinValue;
            if (DateTime.TryParse(date1, out begin) &&
                DateTime.TryParse(date2, out end))
            {
                var list = db.ProductDetails.Where(d => d.Date >= begin.Date && d.Date <= end.Date).AsQueryable();
                if (list != null)
                {
                    if (list.ToList().Count > 0)
                    {
                        var amount = list.Sum(d => d.Amount);
                        return Json(new string[] { amount.ToString() });
                    }
                }
            }
            return Json(new string[]{"0"});
        }

再来写View的Jquery代码

<script>
    $(function () {
        $("#BeginDate").blur(function () {
            CalAmount(this);
        });
        $("#EndDate").blur(function () {
            CalAmount(this);
        });
    });
    function CalAmount(datet) {
        var d1 = $("#BeginDate").val();
        var d2 = $("#EndDate").val();
        
        $.post("/PayRecord/GetAmount", { date1: d1, date2: d2 }, function (aa) {
            if (aa) {
                $("#Amount").val(aa[0]);
            }
        }, "json");
    }

</script>

OK,就这样,就实现效果了,离开焦点的时候就给Amount赋值了,本来想用change事件,没有效果,先用blur先凑合用吧,等找到原因再来改过。

 

posted on 2015-01-20 16:39  如果没有如果  阅读(575)  评论(0编辑  收藏  举报