如何将值Linq传递给控制器​​并传递给视图?

时间:2017-09-10 00:38:27

标签: c# asp.net asp.net-mvc linq

我无法将模型中的数据显示到控制器,并显示在视图中。

模型客户

using System.Collections.Generic;
namespace Train1.Models
{
    public class Customer
    {
        public string CustomerId { get; set; }
        public string CustomerName { get; set; }
        public List<Customer> ListCustomer { get; set; }

        public void CustomerData()
        {
            ListCustomer.Add(new Customer { CustomerId = "C01", CustomerName = "Mike" });
            ListCustomer.Add(new Customer { CustomerId = "C02", CustomerName = "August" });
            ListCustomer.Add(new Customer { CustomerId = "C03", CustomerName = "Jhon" });
            ListCustomer.Add(new Customer { CustomerId = "C04", CustomerName = "Andie" });
        }
    }
}

模型CustomerOrders

namespace Train1.Models
{
    public class CustomerOrders
    {
        public static void GetCustomer() 
        {
            Customer cu = new Customer();
            cu.CustomerData();
            var ListCustomer = from r in cu.ListCustomer select r;
        }
    }
}

控制器

using System.Web.Mvc;
using train1.Models;

namespace train1.Controllers
{
    public class CustomerController : Controller
    {
        // GET: Customer
        public ActionResult Index()
        {
            CustomerOrders cust = new CustomerOrders();
            return View();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果您希望View从Controller接收模型,则需要传递它:

public ActionResult Index()
{
    return View(CustomerOrders.GetCustomer());
}

另请注意GetCustomer()不会返回数据,请将其更改为:

public class CustomerOrders
{
    public static IEnumerable<Customer> GetCustomer() 
    {
        Customer cu = new Customer();
        cu.CustomerData();
        // from r in cu.ListCustomer select r
        return cu.ListCustomer; //no need to use LinQ here
    }
}