AutoMapper使用示例(一)【结合ASP.NET MVC4 】

Model层的类:

public class Member
    {
        public int MemberId { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }

        public int Age { get; set; }

        public string State { get; set; }
    }
  public class MembersViewModel
    {
        public int MemberId { get; set; }

        public string Name { get; set; }
    }
 public class ProfileViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string ProfilePictureUrl { get; set; }
    }
 public class WelcomeViewModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
   public class MemberRepository
    {
        List<Member> _members;

        public MemberRepository()
        {
            _members = new List<Member>();

            _members.Add(new Member
            {
                MemberId = 1,
                FirstName = "天风",
                LastName = "幻灵",
                Age = 28,
                State = "死灵国"
            });

            _members.Add(new Member
            {
                MemberId = 2,
                FirstName = "白龙",
                LastName = "幻灵",
                Age = 15,
                State = "龙之国"
            });

            _members.Add(new Member
            {
                MemberId = 3,
                FirstName = "释天",
                LastName = "幻灵",
                Age = 29,
                State = "天国"
            });
        }

        public Member GetMember(int id)
        {
            return _members.FirstOrDefault(m => m.MemberId == id);
        }


        public List<Member> GetMembers()
        {
            return _members;
        }
    }
HomeController.cs代码如下:
public class HomeController : Controller
    {
        MemberRepository _memberRepository = new MemberRepository();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Welcome()
        {
            var member = _memberRepository.GetMember(1);

            var viewModel = Mapper.Map<Member, WelcomeViewModel>(member);

            return View(viewModel);
        }

        public ActionResult Profile(int id)
        {
            var member = _memberRepository.GetMember(id);

            var viewModel = Mapper.Map<Member, ProfileViewModel>(member);

            viewModel.ProfilePictureUrl = GetProfileImageUrl(member.MemberId);

            return View(viewModel);
        }

        public ActionResult Members()
        {
            var members = _memberRepository.GetMembers();

            var viewModel = Mapper.Map<List<Member>, List<MembersViewModel>>(members);

            return View(viewModel);
        }

        private string GetProfileImageUrl(int id)
        {
            return string.Format("~/Images/Members/{0}/Profile", id);
        }
    }
Index.cshtml
@{
    ViewBag.Title = "Index";
}
<h2>
    Index</h2>
    <p>这是一个简单的AutoMapper例子网站,展示了如何在不同的情况下使用。</p>
    <p>检查映射在Global.asax中是如何创建的,并期待在HomeController中的映射是如何使用的。</p>
    
Members.cshtml
@model List<ViewModels.MembersViewModel>
@{
    ViewBag.Title = "Members";
}
<h2>@ViewBag.Title</h2>
<p>
    下面是我们的会员的完整列表</p>
<ul>
    @foreach (var member in Model)
    {
        <li>@Html.ActionLink(member.Name, "Profile", new { id = member.MemberId })</li>
    }
</ul>
Profile.cshtml
@model ViewModels.ProfileViewModel
@{
    ViewBag.Title = string.Format("{0}的简介", Model.FirstName);
}
<h2>@ViewBag.Title</h2>
<p>
    这是<span style="color:red;"> @Model.FirstName @Model.LastName </span>的个人资料页!</p>
<p>
    他的个人资料图像位于 @Model.ProfilePictureUrl.</p>
Welcome.cshtml
@model ViewModels.WelcomeViewModel
@{
    ViewBag.Title = "Welcome";
}

<h2>@ViewBag.Title</h2>

<p>欢迎来到示例 @Model.FirstName @Model.LastName!</p>
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-2.5.3.js")" type="text/javascript"></script>
</head>
<body>
    <header>
        <h1>AutoMapper 示例</h1>
    </header>
    <nav>
        <ul>
            <li>@Html.ActionLink("欢迎页面", "Welcome")</li>
            <li>@Html.ActionLink("简介页面", "Profile", new { id = 2 })</li>
            <li>@Html.ActionLink("成员列表页面", "Members")</li>
        </ul>
    </nav>
    @RenderBody()
    <footer>
    </footer>
</body>
</html>
Global.asax
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Bootstrap;
using Bootstrap.AutoMapper;
using AutoMapper;
using AutoMapperExample.Dal;
using ViewModels;

namespace AutoMapperExample
{
    public class MvcApplication : HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", 
                "{controller}/{action}/{id}", 
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
            );
        }

        public static void CreateMaps()
        {
            Mapper.CreateMap<Member, WelcomeViewModel>();

            Mapper.CreateMap<Member, ProfileViewModel>()
                .ForMember(dest => dest.ProfilePictureUrl, src => src.Ignore()); //在目标类型我们有个属性ProfilePictureUrl,它有其他的含义(非字面意思或预留字段), 我们不想进行转换


            //Name属性在Source中不存在,如果现在创建映射规则,在映射的时候必然会抛出异常。这个时候我们就需要使用自定义解析器来完成映射。
            Mapper.CreateMap<Member, MembersViewModel>().ForMember(dest => dest.Name, src => src.ResolveUsing(m => string.Format("{0} {1}", m.FirstName, m.LastName)));

            //在程序启动时对所有的配置进行严格的验证
            Mapper.AssertConfigurationIsValid();
        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            CreateMaps();
        }
    }
}
结果如图:

AutoMapper使用示例(一)【结合ASP.NET MVC4 】_第1张图片





你可能感兴趣的:(.net,mvc,C#,AutoMapper,MVC4)