自动调用控制器方法并生成部分视图.如何
本文关键字:成部 视图 如何 调用 控制器 方法 | 更新日期: 2023-09-27 18:36:15
我想在分部视图中自动生成一个列表。
_Layout.cshtml
@Html.Partial("../Transaction/_Transaction")
事务控制器
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
应该如何编码以制作一个没有提交按钮等的简单列表?
一种方法是让页面返回项目列表并将它们输入到您的部分。
function ActionResult GetMainTransactionView()
{
List<Transaction> transactions=GetTransactions();
return PartialView("TransactionIndex",transactions);
}
TransactionIndex.cshtml
@model List<Transaction>
@Html.Partial("../Transaction/_Transaction",model)
Main.chtml
<a id="transactionLink" href='@Url.Action("GetMainTransactionView","Transaction")'/>
您应该调用控制器操作并让它返回分部视图。此外,使用视图模型而不是视图包。
布局或父视图/分部视图:
@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);
}
}