ارسال چند مدل به یک View در MVC

چهارشنبه 15 دی 1395

در این مقاله قصد داریم چگونگی ارسال چند مدل به یک View درMVC را به همراه مثال برای شما توضیح دهیم.به صورت پیش فرض یک view میتواند یک مدل را دریافت کند ولی ما در اینجا میخواهیم چندین مدل را به یک view ارسال کنیم.

ارسال چند مدل به یک View در MVC

پایگاه داده :

در اینجا ما از پایگاه داده Microsoft’s Northwind استفاده میکنیم. شما میتوانید آن را در زیر دانلود کنید.

دانلود و نصب پایگاه داده Northwind 

فضای نام ها :

شما نیاز به وارد کردن فضا نام های زیر دارید.

using System.Dynamic;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;

مدل :

از دو مدل زیر پیروی کنید :

CustomerMode برای قرار دادن داده های مشتری در جدول استفاده شده است.

using System.Dynamic;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generi

EmployeeModel برای  قرار دادن داده های کارمندان در جدول استفاده شده است.

public class EmployeeModel
{
    public string EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

کنترلر :

کنترلر شامل یک متد اکشن index است. نخست یک شی از کلاس ExpandoObject  ساخته شده است که این مشتق شده است ونوع آن dynamic است.

نکته : ExpandoObject   به ما اجازه حذف و اضافه کردن  داینامیک شی ها را در زمان اجرا میدهد. که این در فضای نام System.Dynamic است.

رکورد های جدول Customer با استفاده از ADO.NET واکشی میشوند و توسط یک لیست جنریک به مدل برگردانده میشوند.

کالکشن برگردانده شده ، شی داینامیک کلاس ExpandoObject  را اضافه میکند و به view ارسال مینماید.

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        dynamic model = new ExpandoObject();
        model.Customers = GetCustomers();
        model.Employees = GetEmployees();
        return View(model);
    }
 
    private static List<CustomerModel> GetCustomers()
    {
        List<CustomerModel> customers = new List<CustomerModel>();
        string query = "SELECT TOP 10 CustomerID, ContactName, City, Country FROM Customers";
        string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(new CustomerModel
                        {
                            CustomerId = sdr["CustomerID"].ToString(),
                            CustomerName = sdr["ContactName"].ToString(),
                            City = sdr["City"].ToString(),
                            Country = sdr["Country"].ToString()
                        });
                    }
                }
                con.Close();
                return customers;
            }
        }
    }
 
    private static List<EmployeeModel> GetEmployees()
    {
        List<EmployeeModel> employees = new List<EmployeeModel>();
        string query = "SELECT EmployeeID, (FirstName + ' ' + LastName) [Name], City, Country FROM Employees";
        string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        employees.Add(new EmployeeModel
                        {
                            EmployeeId = sdr["EmployeeID"].ToString(),
                            EmployeeName = sdr["Name"].ToString(),
                            City = sdr["City"].ToString(),
                            Country = sdr["Country"].ToString()
                        });
                    }
                    con.Close();
                    return employees;
                }
            }
        }
    }
}

view : 

در داخل view ، شما نیاز به وارد کردن فضای نام برای دسترسی به کلاس های مدل دارید.

و سپس نیاز به تعریف مدل داخل view به صورت داینامیک دارید.

برای نمایش دادن رکورد ها ، از دو جدول html استفاده شده است

@using Multiple_Model_MVC.Models
@model dynamic
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>CustomerID</th>
            <th>Contact Name</th>
            <th>City</th>
            <th>Country</th>
        </tr>
        @foreach (CustomerModel customer in Model.Customers)
        {
            <tr>
                <td>@customer.CustomerId</td>
                <td>@customer.CustomerName</td>
                <td>@customer.City</td>
                <td>@customer.Country</td>
            </tr>
        }
    </table>
    <hr/>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>EmployeeID</th>
            <th>Employee Name</th>
            <th>City</th>
            <th>Country</th>
        </tr>
        @foreach (EmployeeModel employee in Model.Employees)
        {
            <tr>
                <td>@employee.EmployeeId</td>
                <td>@employee.EmployeeName</td>
                <td>@employee.City</td>
                <td>@employee.Country</td>
            </tr>
        }
    </table>
</body>
</html>

آموزش asp.net mvc

فایل های ضمیمه

برنامه نویسان

نویسنده 3355 مقاله در برنامه نویسان

کاربرانی که از نویسنده این مقاله تشکر کرده اند

در صورتی که در رابطه با این مقاله سوالی دارید، در تاپیک های انجمن مطرح کنید