2014-06-28 44 views
8

Tôi đã làm các hướng dẫn và cố gắng tìm hiểu thực hành tốt nhất khi nói đến phát triển MVC. Các thiết kế tôi đang sử dụng dưới đây đến từ Pro ASP.Net MVC5 bởi Apress/Adam Freeman. Cho đến nay, tất cả mọi thứ đang đến cùng tốt ... nhưng tôi vẫn chưa hoàn toàn đến để làm việc với Controllers. Vâng, tôi hiểu khái niệm về Bộ điều khiển, nhưng vẫn phải vật lộn khi nói đến việc đăng và nhận các phương pháp. Đây là dòng chảy của mẫu ứng dụng MVC của tôi:Ví dụ về MVC ViewModel

dự án app.Domain My

Tôi có một bảng người dùng trong cơ sở dữ liệu và tham khảo nó với Entities/Users.cs

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 

namespace app.Domain.Entities 
{ 
public class Users 
{ 
    [Key] 
    public int UserID { get; set; } 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Email { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public DateTime CreateDate { get; set; } 
    public DateTime LastLogin { get; set; } 

} 
} 

Tiếp theo, tôi có một giao diện và nó nằm Tóm tắt/IUsersRepository.cs

using System; 
using System.Collections.Generic; 
using app.Domain.Entities; 

namespace app.Domain.Abstract 
{ 
public interface IUsersRepository 
{ 
    IEnumerable<Users> Users { get; } 
} 
} 

Moving cùng, bây giờ tôi điền vào đơn vị của tôi bê tông/EFUsersRepository.cs

012.
using System; 
using System.Collections.Generic; 
using app.Domain.Entities; 
using app.Domain.Abstract; 

namespace app.Domain.Concrete 
{ 
public class EFUsersRepository : IUsersRepository 
{ 
    private EFDbContext context = new EFDbContext(); 

    public IEnumerable<Users> Users 
    { 
     get { return context.Users; } 
    } 
} 
} 

Ngoài ra, sách giáo khoa đang sử dụng Ninject mà tôi hiểu và mọi thứ đều bị ràng buộc chính xác. Tôi sẽ không đăng mã đó trừ khi có ai đó hỏi tôi.

Đây là giải pháp app.WebUI của tôi:

Sách giáo khoa hướng dẫn tôi tạo một ViewModel. Đây là nơi mọi thứ trở nên mờ nhạt đối với tôi. ViewModel có phải là kênh bổ sung để lấy các thực thể không? Thay vì tự tham khảo các Mô hình, tôi có nên tạo ViewModels thành dữ liệu SELECT, UPDATE, INSERT, DELETE (Models/UsersViewModel.cs) không?

using System; 
using System.Collections.Generic; 
using app.Domain.Entities; 

namespace app.WebUI.Models 
{ 
public class UsersViewModel 
{ 
    //public string FirstName { get; set; } 
    //public string LastName { get; set; } 
    //public string Email { get; set; } 
    //public string City { get; set; } 
    //public string State { get; set; } 
    public IEnumerable<Users> Users { get; set; } 
} 
} 

Kịch bản dành cho người dùng nhập vào email, sau đó Controller kiểm tra cơ sở dữ liệu cho email. Nếu nó tồn tại, sau đó chuyển hướng đến About View (Controllers/HomeController.cs).

using System.Linq; 
using System.Web.Mvc; 
using app.Domain.Abstract; 
using app.WebUI.Models; 


namespace app.Controllers 
{ 
public class HomeController : Controller 
{ 
    private IUsersRepository repository; 

    public HomeController(IUsersRepository usersRepository) 
    { 
     this.repository = usersRepository; 
    } 

    [HttpGet] 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index() 
    { 
     UsersViewModel userViewModel = new UsersViewModel() 
     { 
      Users = repository.Users 
      .Where(p => p.Email == "[email protected]") 
     }; 
     return View("About", userViewModel); 

    } 

    public ActionResult About() 
    { 
     ViewBag.Message = "Your application description page."; 
     return View(); 
    } 

    public ActionResult Contact() 
    { 
     ViewBag.Message = "Your contact page."; 
     return View(); 
    } 
} 
} 

Và đây là quan điểm của tôi (Home/Index.cshtml):

@model app.WebUI.Models.UsersViewModel 

@{ 
    ViewBag.Title = "Home Page"; 
    Layout = "~/Views/Shared/_LayoutNoMenu.cshtml"; 
} 


@foreach (var p in Model.Users) 
{ 
<div class="container"> 
@using (Html.BeginForm("About", "Home", FormMethod.Get, new { @class = "begin-form" })) 
{ 
    <h1>Welcome</h1> 
    <div class="required-field-block"> 
    <textarea rows="1" class="form-control" placeholder="Email" id="filter"></textarea> 
    </div> 
    <button class="btn btn-primary" type="submit">Login</button> 
} 
</div> 
} 

Bất cứ lời khuyên về cách sử dụng một cách chính xác một ViewModel?

+2

ViewModel là để biểu thị trạng thái của trang của bạn. Ví dụ, nếu bạn có một nút radio trên trang của bạn, viewmodel sẽ có một thuộc tính cho trạng thái của nút radio. Các khung nhìn đơn giản có thể không thực sự có bất kỳ sự cần thiết nào cho một viewmodel, nếu tất cả những gì chúng đang làm là hiển thị trực tiếp các khung nhìn mà không cần thêm công cụ nào. –

+0

Cảm ơn Daniel. Vì vậy, một hộp văn bản trống sẽ không cần một ViewModel. Nhưng một hộp văn bản mà tôi muốn cư trú khi lượt xem tải nên sử dụng một ViewModel? – JoshYates1980

+0

Tôi muốn điền dữ liệu từ cơ sở dữ liệu. – JoshYates1980

Trả lời

8

Vào tháng 6 năm 2014, tôi đã đặt câu hỏi này trong khi học MVC. Tính đến hôm nay, tôi hiểu khái niệm về mô hình viewmodel. Hy vọng rằng điều này sẽ giúp một người mới bắt đầu MVC:

Mô hình của tôi đại diện cho các bảng cơ sở dữ liệu:

public partial class County : Entity 
{ 
    public int CountyID { get; set; } 
    public string CountyName { get; set; } 
    public string UserID { get; set; } 
    public DateTime? CreatedDate { get; set; } 
    public string ModifiedUserID { get; set; } 
    public DateTime? ModifiedDate { get; set; } 

    public virtual IList<Property> Properties { get; set; } 
    public virtual DistrictOffice DistrictOffice { get; set; } 
    public virtual IList<Recipient> Recipients { get; set; } 
} 

Có hai mối quan hệ một-nhiều và mối quan hệ một-một. Khuôn khổ thực thể và tiêm phụ thuộc. (Điều này không cần thiết cho giải thích mô hình xem.)

Trước tiên, tôi tạo chế độ xem để lưu trữ tạm thời để chuyển từ bộ điều khiển sang chế độ xem. CountyViewModel.cs

public class CountyViewModel 
{ 
    [HiddenInput] 
    public int? CountyId { get; set; } 

    [DisplayName("County Name")] 
    [StringLength(25)] 
    public string CountyName { get; set; } 

    [DisplayName("Username")] 
    [StringLength(255)] 
    public string Username{ get; set; } 
} 

Bạn có thể linh động sử dụng tên và kiểu dữ liệu khác với mô hình của bạn. Ví dụ, cột cơ sở dữ liệu của tôi là UserID, mô hình của tôi là UserID, nhưng viewmodel của tôi là UserName. Và bạn không cần truyền dữ liệu cho Chế độ xem sẽ không được sử dụng (toàn bộ mô hình.) Ví dụ này chỉ cần ba phần của mô hình Quận.

Trong vòng điều khiển của tôi, tôi tuyên bố mô hình quan điểm của tôi:

Tôi cần dữ liệu:

var county = _countyService.Get(countyId); 

Tiếp theo,

CountyViewModel countyViewModel = new CountyViewModel(); 
countyViewModel.CountyId = county.CountyID; 
countyViewModel.CountyName = county.CountyName; 
countyViewModel.UserName = county.UserID; 

Bạn cũng có thể tuyên bố như sau:

CountyViewModel countyViewModel = new CountyViewModel 
{ 
    CountyId = county.CountyID, 
    CountyName = county.CountyName, 
    UserName = county.UserID 
}; 

Bây giờ là thời gian để vượt qua trên các Xem:

return View(countyViewModel); 

Trong Xem:

@model Project.Web.ViewModels.CountyViewModel 

@{ 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<div>@Model.CountyName</div> 
@Html.HiddenFor(model => model.CountyId) 

<div> 
@Html.TextBoxFor(model => model.CountyName, new { @class = "form-control" }) 

Đây là một ví dụ đơn giản thông qua dữ liệu sử dụng một viewmodel và sử dụng dịch vụ cuộc gọi đến cơ sở dữ liệu với Entity Framework:

Ví dụ khiển

public class PropertyController : Controller 
{ 
    private readonly ICountyService _countyService; 

    public PropertyController(ICountyService countyService) 
     : base() 
    { 
     _countyService = countyService; 
    } 


    [HttpGet] 
    public ActionResult NewProperty() 
    { 
     using (UnitOfWorkManager.NewUnitOfWork()) 
     { 
      ListAllCountiesViewModel listAllCountyViewModel = new ListAllCountiesViewModel() 
      { 
       ListAllCounty = _countyService.ListOfCounties().ToList() 
      }; 

      PropertyViewModel viewModel = new PropertyViewModel() 
      { 
       _listAllCountyViewModel = listAllCountyViewModel, 
       _countyViewModel = new CountyViewModel(), 
      }; 
      return View(viewModel); 
     } 
    } 
} 

Ví dụ ViewModels

public class CountyViewModel 
{ 
    [HiddenInput] 
    public int? CountyId { get; set; } 

    [DisplayName("County Name")] 
    [StringLength(25)] 
    public string CountyName { get; set; } 

    [DisplayName("County URL")] 
    [StringLength(255)] 
    public string URL { get; set; } 
} 

public class ListAllCountiesViewModel 
{ 
    public string CountyName { get; set; } 
    public IEnumerable<County> ListAllCounty { get; set; } 
} 

public class PropertyViewModel 
{ 
    public ListAllCountiesViewModel _listAllCountyViewModel { get; set; } 
    public CountyViewModel _countyViewModel { get; set; } 
} 

Ví dụ lớp Service

public partial interface ICountyService 
{ 
    County Get(int id); 
    County GetByCompanyCountyID(int id); 
    IEnumerable<County> ListOfCounties(); 
    void Delete(County county); 
    IEnumerable<State> ListOfStates(); 
    void Add(County county); 
    County SearchByName(string county); 
} 


public partial class CountyService : ICountyService 
{ 
    private readonly ICountyRepository _countyRepository; 

    public CountyService(ICountyRepository countryRepository) 
    { 
     _countyRepository = countryRepository; 
    } 

    /// <summary> 
    /// Returns a county 
    /// </summary> 
    /// <param name="id"></param> 
    /// <returns></returns> 
    public County Get(int id) 
    { 
     return _countyRepository.Get(id); 
    } 

    /// <summary> 
    /// Returns a county by County Id 
    /// </summary> 
    /// <param name="id"></param> 
    /// <returns></returns> 
    public County GetByCountyID(int id) 
    { 
     return _countyRepository.GetByMedicaidCountyID(id); 
    } 

    /// <summary> 
    /// Returns all counties 
    /// </summary> 
    /// <returns></returns> 
    public IEnumerable<County> ListOfCounties() 
    { 
     return _countyRepository.ListOfCounties(); 
    } 

    /// <summary> 
    /// Deletes a county 
    /// </summary> 
    /// <param name="county"></param> 
    public void Delete(County county) 
    { 
     _countyRepository.Delete(county); 
    } 

    /// <summary> 
    /// Return a static list of all U.S. states 
    /// </summary> 
    /// <returns></returns> 
    public IEnumerable<State> ListOfStates() 
    { 
     var states = ServiceHelpers.CreateStateList(); 
     return states.ToList(); 
    } 

    /// <summary> 
    /// Add a county 
    /// </summary> 
    /// <param name="county"></param> 
    public void Add(County county) 
    { 
     county.CreatedUserID = System.Web.HttpContext.Current.User.Identity.Name; 
     county.CreatedDate = DateTime.Now; 
     _countyRepository.Add(county); 
    } 

    /// <summary> 
    /// Return a county by searching it's name 
    /// </summary> 
    /// <param name="county"></param> 
    /// <returns></returns> 
    public County SearchByName(string county) 
    { 
     return _countyRepository.SearchByName(county); 
    } 
} 

Ví dụ lớp Repository

public partial class CountyRepository : ICountyRepository 
{ 
    private readonly Context _context; 

    public CountyRepository(IContext context) 
    { 
     _context = context as Context; 
    } 

    public County Get(int id) 
    { 
     return _context.County.FirstOrDefault(x => x.CountyID == id); 
    } 

    public County GetByCompanyCountyID(int id) 
    { 
     return _context.County.FirstOrDefault(x => x.CountyID == id); 
    } 

    public IList<County> ListOfCounties() 
    { 
     return _context.County.ToList() 
      .OrderBy(x => x.CountyName) 
      .ToList(); 
    } 

    public void Delete(County county) 
    { 
     _context.County.Remove(county); 
    } 

    public County Add(County county) 
    { 
     _context.County.Add(county); 
     return county; 
    } 

    public County SearchByName(string county) 
    { 
     return _context.County.FirstOrDefault(x => x.CountyName == county); 
    } 
} 
+0

Josh, "_countyService" xuất phát từ đâu? Chỉ đề cập đến bạn làm cho nó là trong việc sử dụng nó. – muybn

+0

Tôi đã cập nhật câu trả lời của mình với ví dụ về cách _countyService nhận dữ liệu của tôi. – JoshYates1980

+0

Các lớp dịch vụ đó có cần thiết không? Bạn không thể chỉ gọi 'DbContext' của bạn? – Sinjai