ASP.Net MVC 后台数据传递到前台方法

Controller与View的数据传递

1.ViewBag与ViewData

Controller传递数据至View的方法相当多。从ASP.Net MVC1开始,要有Controller传递资料给View,可以使用ViewData、TempData两种属性。在ASP.Net MVC3时,还新增了ViewBag属性。

public ActionResult Index()
{
    
    
    ViewBag.Name = "Merry";
    ViewData["Age"] = 20;

    return View();
}

@{
    ViewBag.Title = "Index";
}

<h2>Index1</h2>

Age:@ViewData["Age"]

Name:@ViewBag.Name

2.ViewData.Model

因为ViewData属性是ViewDataDictionary类型,在存储数据时使用Object类型,这种弱类型的存储与传递方式不方便,必须使用类型转换。也可以使用ViewData.Model属性帮忙传递。

注意1:MVC的View技术中,@model关键词可以将ViewPage指定为某种特定的类型,指定之后,当从Controller将Model数据传递给ViewPage时,ViewPage自动进行类型转换,这位开发者在编写Razor带来了很大的方便。
注意2:一个ViewPage只能声明一个@model关键词。
注意3:@model 声明没有分号,不要写 “;”。

例子1:

private Entities db = new Entities();
public ActionResult Index()
{
    
    
    ViewData.Model = db.UserInfo.ToList();
    return View();
}
@model IEnumerable<WebApplication18.Models.UserInfo>

<table class="table">
    <tr>
        <th>Name</th><th>Password</th>          
    </tr>

    @foreach (var item in Model) 
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Password </td>
        </tr>
    }
</table>

例子2:联合数据查询,定义ViewModel

namespace WebApplication18.ViewModel
{
    
    
    public class UserViewModel
    {
    
    
        public string ID {
    
     get; set; }
        public string Name {
    
     get; set; }
        public string Password {
    
     get; set; }
        public string City {
    
     get; set; }
    }
}
public class UserInfoController : Controller
{
    
    
    private Entities db = new Entities();

    public ActionResult Index()
    {
    
    
       	//慎用select New{},不要写成匿名对象,否则无法转换ViewModel类型的对象
        var query = from itemA in db.Address
                    join itemB in db.UserInfo on itemA.Name equals itemB.Name
                    orderby itemA.ID descending
                    select new UserViewModel() {
    
     
                    ID = itemA.ID.ToString(), 
                    Name = itemA.Name, 
                    Password = itemB.Password, 
                    City = itemA.City };

        return View(query.ToList<UserViewModel>());          
    } 
    
    protected override void Dispose(bool disposing)
    {
    
    
        if (disposing)
        {
    
    
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
@model IEnumerable<WebApplication.ViewModel.UserViewModel>

<html>
<head>
    <script type="text/javascript" src="~/Scripts/jquery-3.4.1.js"></script>
</head>
<body>
    <h2>This is a test</h2>
    <h4>UserInfo</h4>
    <br/>
    <table class="table">
        <thead>
            <tr>
                <td>ID</td><td>Name</td><td>Password</td><td>City</td>
            </tr>
        </thead>
        <tbody id="content">
            @foreach(var item in Model)
            {
                <tr>
                    <td>@item.ID</td>
                    <td>@item.Name</td>
                    <td>@item.Password</td
                    ><td>@item.City</td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>

3.多对象传递-ViewModel

ViewModel是一个很特别的类,类似于“定制化”,就是专为某个View定制化的类,这样的类通常就只定义某个View呈现所需的属性,正式的说,ViewModel应该只封装属性,本质上是一种DTO数据传递对象应用,ViewModel与View最好是一对一关系,尽量简单,不要用多个View去共享一个ViewModel。

namespace WebApplication18.ViewModel
{
    
    
    public class UserViewModel
    {
    
    
        public IEnumerable<UserInfo> UserInfos {
    
     get; set; }
        public IEnumerable<Address> Addresses {
    
     get; set; }
    }
}
public ActionResult Index()
{
    
    
     return View(new UserViewModel()
     {
    
    
         UserInfos = db.UserInfo.ToList(),
         Addresses = db.Address.ToList()
     });
 }
@model WebApplication18.ViewModel.UserViewModel

<html>
<head>
    <script type="text/javascript" src="~/Scripts/jquery-3.4.1.js"></script>
</head>
<body>
    <h2>This is a test</h2>
    <h4>UserInfo</h4>
    <br/>
    <table class="table">
        <thead>
            <tr>
                <td>ID</td><td>Name</td><td>Password</td>
            </tr>
        </thead>
        <tbody id="content">
            @foreach(var item in Model.UserInfos)
            {
                <tr>
                    <td>@item.ID</td><td>@item.Name</td><td>@item.Password</td>
                </tr>
            }
        </tbody>
    </table>

    <table class="table">
        <thead>
            <tr>
                <td>ID</td><td>Name</td><td>City</td>
            </tr>
        </thead>
        <tbody id="content">
            @foreach(var item in Model.Addresses)
            {
                <tr>
                    <td>@item.ID</td><td>@item.Name</td><td>@item.City</td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>

4.多对象传递-Tuple元组

public ActionResult Index()
{
    
    
    List<UserInfo> userInfos = db.UserInfo.ToList();
    List<Address> addresses = db.Address.ToList();
	//方法1
    var tupleModel = new Tuple<List<UserInfo>, List<Address>>(userInfos, addresses);
    //方法2
    var tupleModel1 = Tuple.Create(userInfos, addresses);
    
    return View(tupleModel);
}
@model Tuple<List<WebApplication18.Models.UserInfo>,List<WebApplication18.Models.Address>>

<html>
<head>
    <script type="text/javascript" src="~/Scripts/jquery-3.4.1.js"></script>
</head>
<body>
    <h2>This is a test</h2>
    <h4>UserInfo</h4>
    <br/>
    <table class="table">
        <thead>
            <tr>
                <td>ID</td><td>Name</td><td>Password</td>
            </tr>
        </thead>
        <tbody id="content">
            @foreach(var item in Model.Item1)
            {
                <tr>
                    <td>@item.ID</td><td>@item.Name</td><td>@item.Password</td>
                </tr>
            }
        </tbody>
    </table>

    <table class="table">
        <thead>
            <tr>
                <td>ID</td><td>Name</td><td>City</td>
            </tr>
        </thead>
        <tbody id="content">
            @foreach(var item in Model.Item2)
            {
                <tr>
                    <td>@item.ID</td><td>@item.Name</td><td>@item.City</td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>

5.多对象传递-AJAX

注意:2种动态插入表格写法

public ActionResult Index()
{
    
                        
    return View();
}
public ActionResult IndexInitial()
{
    
    
    var query = from itemA in db.Address
                join itemB in db.UserInfo on itemA.Name equals itemB.Name
                orderby itemA.ID descending
                select new {
    
     
                    id = itemA.ID, 
                    name = itemA.Name, 
                    password = itemB.Password, 
                    city = itemA.City };

    JsonResult jsonResult = new JsonResult();
    jsonResult.Data = query.ToList();
    jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    return jsonResult;
}
<html>
<head>
    <script type="text/javascript" src="~/Scripts/jquery-3.4.1.js"></script>
</head>
<body>
    <h2>This is a test</h2>
    <h4>UserInfo</h4>
    <br/>
    <table class="table">
        <thead>
            <tr>
                 <td>ID</td><td>Name</td><td>Password</td><td>City</td>
            </tr>
        </thead>
        <tbody id="content1"></tbody>
    </table>

    <table class="table">
        <thead>
            <tr>
                <td>ID</td><td>Name</td><td>Password</td><td>City</td>
            </tr>
        </thead>
        <tbody id="content2"></tbody>
    </table>

    <a href="/UserInfo/Details?ID=1&Name=Lily">Details</a>
    <script type="text/javascript">
        $(function () {
     
     
            $.ajax({
     
     
                url: "UserInfo/IndexInitial",
                type: "Get",
                dataType: "json",
                async: "true",
                success: function (data, state) {
     
                         
                    $.each(data, function (index, content) {
     
     
                        var $tr = $('<tr></tr>');
                        $tr.append('<td>' + index + '</td>');
                        $tr.append('<td>' + content.name + '</td>');                  
                        $tr.append('<td>' + content.password + '</td>');
                        $tr.append('<td>' + content.city + '</td>');                       
                        $("#content1").append($tr);                       
                    });

                    var html = "";
                    $.each(data, function (index, content) {
     
     
                        html += "<tr>";
                        html += "<td>" + content.id + "</td>";
                        html += "<td>" + content.name + "</td>";
                        html += "<td>" + content.password + "</td>";
                        html += "<td>" + content.city + "</td>";
                        html += "</tr>";
                    });
                    $("#content2").html(html);                   
                }
            })
        })
    </script>
</body>
</html>

Happy Ending

猜你喜欢

转载自blog.csdn.net/ryancao530/article/details/111603816