asp.net mvc c#的控制器不能调用模型中的方法
本文关键字:调用 模型 方法 不能 控制器 net mvc asp | 更新日期: 2023-09-27 18:18:02
这是我的模型中的方法:
public IList<Customer> GetProfileCustomer(int id)
{
var list_customer = from c in DataContext.Customers
where c.ID == id
select c;
return list_customer.ToList();
}
这就是我在控制器中所做的:
public ActionResult ShowProfile()
{
List<CustomerModels> cus = new List<CustomerModels>();
return View();
}
我创建对象是为了调用模型中的GetProfileCustomer()方法,但是我不能这样做。当我写:因为。
你的主要问题是:
List<CustomerModels> cus = new List<CustomerModels>();
这不是创建CustomerModels
的实例,所以你不能在它上面调用那个方法。你必须这样做:
public ActionResult ShowProfile()
{
cus = new CustomerModels();
var data = cus.GetProfileCustomer(123);
return View(data);
}
然而,在MVC的意义上,我不认为从你的模型加载数据是真正正确的方法。通常,控制器有一些对加载和保存数据的其他东西的引用。Model通常只是一个带有保存数据的属性的类。
我会看一下"NerdDinner"示例项目。例如,在这些文件中:
- DinnersController.cs (controller)
- Dinner.cs(模型)
注意,DinnersController
持有对晚餐存储库的引用,这是查询数据库的东西。
AVD是对的,您需要首先实例化包含GetProfileCustomer方法的类,即:
public ActionResult ShowProfile(int id)
{
var model = new WhateverTheClassNameIs().GetProfileCustomer(id);
return View(model);
}
可能您必须创建CustomerModels
的实例而不是List<CustomerModels>
。
public ActionResult ShowProfile()
{
CustomerModels cus=new CustomerModels();
var list=cus.GetProfileCustomer(1); // 1 is value of ID
return View(list);
}
你可以迭代Model in view (Razor)
<div>
@foreach(var cust in Model){
<br /><b>ID :</b> @cust.CustomerID
}
</div>
ASPX标记
<div>
<% foreach (var cust in Model)
{ %>
<br />ID : <%:cust.CustomerID %>
<% } %>
</div>