2010-03-27 97 views
8

Tôi có một bảng cơ sở dữ liệu ghi lại những ấn phẩm mà người dùng được phép truy cập. Bảng này là rất đơn giản - nó chỉ đơn giản là lưu trữ cặp ID ID người dùng/ấn phẩm:Làm cách nào để tạo danh sách lựa chọn bằng các hộp kiểm trong ASP.NET MVC?

CREATE TABLE UserPublication (UserId INTEGER, PublicationID INTEGER) 

Sự hiện diện của một kỷ lục đối với mỗi user & bản có nghĩa là người dùng có quyền truy cập; sự vắng mặt của một hồ sơ ngụ ý không có quyền truy cập.

Tôi muốn giới thiệu cho người dùng quản trị của mình một màn hình đơn giản cho phép họ định cấu hình các ấn bản mà người dùng có thể truy cập. Tôi muốn hiển thị một hộp kiểm cho từng ấn phẩm có thể và kiểm tra những ấn phẩm mà người dùng hiện có thể truy cập. Người dùng quản trị có thể kiểm tra hoặc bỏ chọn bất kỳ số lượng ấn phẩm nào và gửi biểu mẫu.

Có nhiều loại ấn phẩm khác nhau và tôi muốn nhóm các ấn phẩm tương tự với nhau - vì vậy tôi cần kiểm soát cách ấn phẩm được xuất bản (Tôi không muốn chỉ có một danh sách phẳng).

Mô hình chế độ xem của tôi rõ ràng cần có danh sách tất cả các ấn phẩm (vì tôi cần hiển thị tất cả các trang này bất kể lựa chọn hiện tại), và tôi cũng cần danh sách các ấn phẩm mà người dùng hiện có quyền truy cập. (Tôi không chắc liệu mình có tốt hơn với một danh sách duy nhất trong đó mỗi mục bao gồm ID xuất bản và trường có/không?).

Nhưng đó là như xa như tôi đã có. Tôi thực sự không có ý tưởng làm thế nào để đi về ràng buộc này với một số hộp kiểm. Tôi bắt đầu từ đâu?

Trả lời

19

LINQ to SQL mô hình cho vấn đề của bạn trông giống như sau:

alt text http://i39.tinypic.com/m78d1y.jpg

Đầu tiên, chúng ta cần một số helper đối tượng trong mô hình dữ liệu của chúng tôi:

namespace SelectProject.Models 
{ 
    public class UserPublicationSelector 
    { 
     public int UserPublicationID { get; set; } 
     public int UserID { get; set; } 
     public int PublicationID { get; set; } 
     public string PublicationName { get; set; } 
     public bool IsSelected { get; set; } 
    } 

    public class UserPublicationSelectViewModel 
    { 
     public User User { get; set; } 
     public IQueryable Selections { get; set; } 
    } 
} 

Bây giờ hãy tạo một kho trông giống như sau:

public class Repository 
{ 
    DataContext dc = new DataContext(); 

    public User GetUser(int userID) 
    { 
     return dc.Users.FirstOrDefault(u => u.UserID == userID); 
    } 

    public IQueryable GetUserPublications(int userID) 
    { 
     return from p in dc.Publications 
       join up in dc.UserPublications on p.PublicationID equals up.PublicationID 
       where up.UserID == userID 
       orderby p.PublicationName 
       select p; 
    } 
    public IQueryable GetUserPublicationSelectors(int userID) 
    { 
     return from p in dc.Publications 
       join up in dc.UserPublications on p.PublicationID equals up.PublicationID into selected 
       from s in selected.DefaultIfEmpty() 
       orderby p.PublicationName 
       select new UserPublicationSelector 
       { 
        UserPublicationID = (int?)s.UserPublicationID ?? 0, 
        UserID = userID, 
        PublicationID = p.PublicationID, 
        PublicationName = p.PublicationName, 
        IsSelected = s.UserID != null 
       }; 
    } 

    public void UpdateUserPublications(UserPublicationSelector[] selections) 
    { 
     // Insert records for new selections... 
     foreach (UserPublicationSelector selection in selections.Where(s => s.IsSelected == true)) 
     { 
      // ...where records do not yet exist in database. 
      if (selection.UserPublicationID == 0) 
      { 
       UserPublication up = new UserPublication 
       { 
        UserID = selection.UserID, 
        PublicationID = selection.PublicationID, 
       }; 
       dc.UserPublications.InsertOnSubmit(up); 
      } 
     } 
     // Delete records for unselected items... 
     foreach (UserPublicationSelector selection in selections.Where(s => s.IsSelected == false)) 
     { 
      // ...where record exists in database. 
      if (selection.UserPublicationID > 0) 
      { 
       UserPublication up = dc.UserPublications.FirstOrDefault(s => s.UserPublicationID == selection.UserPublicationID); 
       if (up.UserID == selection.UserID && up.PublicationID == selection.PublicationID) 
        dc.UserPublications.DeleteOnSubmit(up); 
      } 
     } 
     // Update the database 
     dc.SubmitChanges(); 
    } 
} 

Và một khiển trông như thế này:

public class PublicationController : Controller 
{ 
    Repository repository = new Repository(); 

    public ActionResult Index(int id) 
    { 
     User user = repository.GetUser(id); 
     var publications = repository.GetUserPublications(id); 
     ViewData["UserName"] = user.UserName; 
     ViewData["UserID"] = user.UserID; 
     return View("Index", publications); 
    } 

    [AcceptVerbs(HttpVerbs.Get)] 
    public ActionResult Select(int id) 
    { 
     var viewModel = new UserPublicationSelectViewModel() 
     { 
      User = repository.GetUser(id), 
      Selections = repository.GetUserPublicationSelectors(id) 
     }; 
     return View("Select", viewModel); 
    } 

    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult Select(int userID, UserPublicationSelector[] selections) 
    { 
     repository.UpdateUserPublications(selections); 
     return RedirectToAction("Index", new { id = userID }); 
    } 
} 

Quan điểm Index trông như thế này:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Publication>>" %> 
<%@ Import Namespace="SelectProject.Models" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
    List of Selected Publications for User 
</asp:Content> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

    <h2>Publications for <%= ViewData["UserName"] %></h2> 

     <table id="MyTable" style="width: 100%"> 
      <thead> 
       <tr> 
        <th> 
         Publication Name 
        </th> 
       </tr> 
      </thead> 

      <tbody> 
       <% int i = 0; 
        foreach (Publication item in Model) 
        { %> 

        <tr id="row<%= i.ToString() %>"> 
         <td> 
          <%= Html.Encode(item.PublicationName)%> 
         </td> 
        </tr> 

        <% i++; 
        } %> 
      </tbody> 
     </table> 
     <p> 
      <%= Html.ActionLink("Edit Selections", "Select", new { id = ViewData["UserID"] })%> 
     </p> 

</asp:Content> 

Chọn xem trông như thế này:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<UserPublicationSelectViewModel>" %> 
<%@ Import Namespace="SelectProject.Models" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> 
    Select Publications 
</asp:Content> 

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 

    <h2>Select Publications for <%= Model.User.UserName %></h2> 

    <% using (Html.BeginForm()) 
     { %> 

     <table id="MyTable" style="width: 100%"> 
      <thead> 
       <tr> 
        <th style="width: 50px; text-align:center"> 
         <input type="checkbox" id="SelectAll" /> 
        </th> 
        <th> 
         Publication Name 
        </th> 
       </tr> 
      </thead> 

      <tbody> 
       <% int i = 0; 
        foreach (UserPublicationSelector item in Model.Selections) 
        { %> 

        <tr id="row<%= i.ToString() %>"> 
         <td align="center" style="padding: 0 0 0 0"> 
          <%= Html.CheckBox("selections[" + i.ToString() + "].IsSelected", item.IsSelected)%> 
          <%= Html.Hidden("selections[" + i.ToString() + "].UserPublicationID", item.UserPublicationID)%> 
          <%= Html.Hidden("selections[" + i.ToString() + "].UserID", Model.User.UserID)%> 
          <%= Html.Hidden("selections[" + i.ToString() + "].PublicationID", item.PublicationID)%> 
         </td> 
         <td> 
          <%= Html.Encode(item.PublicationName)%> 
         </td> 
        </tr> 

        <% i++; 
        } %> 
      </tbody> 
     </table> 
     <p> 
      <%= Html.Hidden("userID", Model.User.UserID) %> 
      <input type="submit" value="save" /> 
     </p> 

    <% } // End Form %> 

    <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script> 

    <script type="text/javascript"> 
     // Select All Checkboxes 
     $(document).ready(function() { 
      $('#SelectAll').click(function() { 
       var newValue = this.checked; 
       $('input:checkbox').not('input:hidden').each(function() { 
        this.checked = newValue; 
       }); 
      }); 
     }); 
    </script> 

</asp:Content> 

Dưới đây là một số ảnh chụp màn hình .

alt text http://i43.tinypic.com/2yl07kw.jpg

alt text http://i44.tinypic.com/mhulua.jpg

Hộp kiểm ở góc trên bên trái là một Select All/Chọn None hộp kiểm.

+0

Câu trả lời thú vị, cảm ơn. Tôi cảm thấy hơi bẩn, giống như tôi đã trả tiền cho bạn để làm bài tập ở nhà của tôi :-) –

+0

Hi Robert, Xuất sắc trong câu trả lời sâu sắc! Cảm ơn bạn .. Làm cách nào để đăng lại (lưu) Chọn hộp có giá trị được chọn? – TonyP

+1

@TonyP: Chức năng đó là trong chế độ xem Chọn, phương pháp điều khiển 'Chọn' với giá trị thuộc tính 'AcceptVerbs HttpVerbs.Post' trên đó và phương thức kho lưu trữ UpdateUserPublications, minh họa ở trên. –

Các vấn đề liên quan