简体   繁体   中英

Can not call the method in model to the controller of asp.net mvc c#

This is the method in my Model :

 public IList<Customer> GetProfileCustomer(int id)
    {
        var list_customer = from c in DataContext.Customers
                            where c.ID == id
                            select c;
        return list_customer.ToList();
    }

And this is what I did in my controller :

   public ActionResult ShowProfile()
    {
        List<CustomerModels> cus = new List<CustomerModels>();

        return View();
    }

I created the object cus to call the method GetProfileCustomer() in the model, but I cannot do that. When I write : cus.GetProfileCustomer, It is error.

Your major issue is the line:

List<CustomerModels> cus = new List<CustomerModels>();

That is not creating an instance of CustomerModels , so you can't call that method on it. You would have to do something like:

public ActionResult ShowProfile()
{
    cus = new CustomerModels();
    var data = cus.GetProfileCustomer(123);
    return View(data);
}

However , in the MVC sense, I don't think loading data from your Model is really the right approach. Typically the Controller has some reference to something else that loads and saves data. The Model is usually just a class with properties to hold the data.

I would look at the " NerdDinner " sample project. For example, in these files:

Note that DinnersController holds a reference to a dinner repository, which is the thing that queries the database.

May be you have to create instance of CustomerModels instead of List<CustomerModels> .

public ActionResult ShowProfile()
    {
        CustomerModels cus=new CustomerModels(); 
        var list=cus.GetProfileCustomer(1); // 1 is value of ID
        return View(list);
    }

You can iterate Model in view (Razor)

  <div>
        @foreach(var cust in Model){
            <br /><b>ID :</b> @cust.CustomerID
             }
    </div>

ASPX markup

<div>
      <% foreach (var cust in Model)
         { %>

         <br />ID : <%:cust.CustomerID %>

      <% } %>
    </div>

AVD is right, You will need to first instantiate the class that houses the GetProfileCustomer method ie:

public ActionResult ShowProfile(int id)
{
    var model = new WhateverTheClassNameIs().GetProfileCustomer(id);

    return View(model);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM