自动调用控制器方法并生成局部视图。怎么样?

时间:2013-10-21 22:35:43

标签: c# ajax asp.net-mvc json razor

我想在局部视图中自动生成一个列表。

_Layout.cshtml

@Html.Partial("../Transaction/_Transaction")

TransactionController

public JsonResult transactionlist()
        {
            List<Transaction> TransactionList = new List<Transaction>().ToList();
            string Usercache = MemoryCache.Default[User.Identity.Name] as string;

            int UsercacheID = Convert.ToInt32(Usercache);
            if (Usercache == null)
            {
                int UserID = (from a in db.UserProfiles
                              where a.UserName == User.Identity.Name
                              select a.UserId).First();
                UsercacheID = UserID;
                MemoryCache.Default[User.Identity.Name] = UsercacheID.ToString();
            }
            var Account = (from a in db.UserAccount
                           where a.UserId == UsercacheID
                           select a).First();

            var DBTransaction = from a in db.Transaction
                                where a.AccountId == Account.AccountId
                                select a;

            var DBTransactionList = DBTransaction.ToList();
            for (int i = 0; i < DBTransactionList.Count; i++)
            {
                TransactionList.Add(DBTransactionList[i]);
            }
            ViewBag.acountsaldo = Account.Amount;

            return Json(TransactionList, JsonRequestBehavior.AllowGet);
        }`

如何对我的_Transaction.cshtml进行编码,以便在没有提交按钮等的情况下制作一个简单的列表?

2 个答案:

答案 0 :(得分:4)

您应该调用控制器操作并让它返回您的局部视图。另外,使用视图模型而不是viewbag。

布局或父视图/局部视图:

@Html.Action("Transaction", "YourController")

部分观点:

@model TransactionModel
@foreach (Transaction transaction in Model.TransactionList) {
    // Do something with your transaction here - print the name of it or whatever
}

查看型号:

public class TransactionModel {
    public IEnumerable<Transaction> TransactionList { get; set; }
}

控制器:

public class YourController
{
    public ActionResult Transaction()
        {
            List<Transaction> transactionList = new List<Transaction>().ToList();
            // Your logic here to populate transaction list
            TransactionModel model = new TransactionModel();
            model.TransactionList = transactionList;

            return PartialView("_Transaction", model);
        }
}

答案 1 :(得分:3)

一种方法是让页面返回一个项目列表并将它们提供给您的部分。

function ActionResult GetMainTransactionView()
{
  List<Transaction> transactions=GetTransactions();
  return PartialView("TransactionIndex",transactions);
}

交易Index.html

@model List<Transaction>
@Html.Partial("../Transaction/_Transaction",model)

Main.chtml

<a id="transactionLink" href='@Url.Action("GetMainTransactionView","Transaction")'/>