2012-08-01 3 views
1

컨트롤러 메소드에 JSON 객체 목록을 전달하려고 시도하고 컨트롤러에 올바른 유형이 정의되고 채워집니다. 컨트롤러에 게시사용자 정의 모델 바인딩 MVC

JSON :

{ Type : 'Image', ImageName : 'blah.jpg' }, 
{ Type : 'Text', Text: 'Hello', Font: 'Some Font' }.. 

컨트롤러 :

public ActionResult SaveCOntent(IList<Item> content) 

그래서 내가있어 느낌이 나는 올바른 유형으로 요소를 변환 ModelBinding를 사용할 필요가있다. 나는 다른 제안 된 게시물 (http://stackoverflow.com/questions/6484972/viewmodel-with-listbaseclass-and-editor-templates)을 따라 노력했는데, 그것은 어떤 방식 으로든 작동한다. 올바른 유형의 목록을 얻는다. '그러나 모든 속성은 기본값으로 설정되고 채워지지 않습니다.

내가 가진 DefaultModelBinder을 확장 시도한 다음

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var typeName = (string)bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".ItemTypeName").ConvertTo(typeof(string)); 

     if (typeName == "LINK") 
     { 

      bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new Link(), typeof(Link)); 

      base.BindModel(controllerContext, bindingContext); 
     } 
     else if (typeName == "IMAGE") 
     { 
      //bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => new Image(), typeof(Image)); 
      //base.BindModel(controllerContext, bindingContext); 
      return null; 

     } 

     return base.BindModel(controllerContext, bindingContext); 
    } 

이제이 첫 번째 유형 (링크)에 대한 잘 작동하지만 최대한 빨리 이미지를 위해 동일한 작업을 수행하려고 나는이 오류를 진술하는

동일한 열쇠를 가진 품목은 이미 추가되었습니다.

+0

똑같은 핵심 오류를 일으키는 것을 발견하고, 기본적으로 상속의 여러 단계에서 같은 이름을 가진 두 개의 속성을가집니다. 그래도이 작업을 수행하는 더 좋은 방법이 있습니까? – BenW

답변

1

밝혀 졌 내 문제는 동일한 이름을 가진 속성을 가진이 개체의 기본 클래스에있었습니다.

0

---------------- 데이터 모델 -> 사용자 지정 폴더 -> UserModel.cs ---------------

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace SamarpanInfotech.DataModel 
{ 
    public class UserModel 
    { 
     public Guid Id { get; set; } 

     public string FirstName { get; set; } 

     public string LastName { get; set; } 

     [Required(ErrorMessage = "Please Enter CurrentPassword")] 
     public string CurrentPassword { get; set; } 

     [Required(ErrorMessage = "Please Enter ChangePassword")] 
     public string ChangePassword { get; set; } 

     [Required(ErrorMessage = "Please Enter ConfirmPassword")] 
     [CompareAttribute("ChangePassword", ErrorMessage = "The Change password and Confirmation password does not match.")]  
     public string ConfirmPassword { get; set; } 

    } 
} 

---------------- 데이터 모델 -> 사용자 지정 폴더 -> RoleRightListModel.cs ---------------

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.ComponentModel.DataAnnotations; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace SamarpanInfotech.DataModel 
{ 


    public class RoleRightListModel 
    { 
     public Guid RoleId { get; set; } 

     public Guid RoleParentId { get; set; } 

     [Required(ErrorMessage = "Please Select Role Code")] 
     [DisplayName("Role Code")] 
     public string RoleCode { get; set; } 

     [Required(ErrorMessage = "Please Select Role Name")] 
     [DisplayName("Role Name")] 
     public string RoleName { get; set; } 

     [DisplayName("About Role")] 
     public string AboutRole { get; set; } 

     public List<RightModel> RightModel { get; set; } 

    } 

    public class RightModel 
    { 
     public string RightName { get; set; } 

     public bool IsAllRight { get; set; } 

     public bool IsViewRight { get; set; } 

     public bool IsAddRight { get; set; } 

     public bool IsEditRight { get; set; } 

     public bool IsDeleteRight { get; set; } 

     public Guid FkRoleId { get; set; } 

     public bool IsAllVisible { get; set; } 

     public bool IsViewVisible { get; set; } 

     public bool IsAddVisible { get; set; } 

     public bool IsEditVisible { get; set; } 

     public bool IsDeleteVisible { get; set; } 

     public Guid RightId { get; set; } 

     public string RightCode { get; set; } 

     public string MenuName { get; set; } 

     public string Descritption { get; set; } 

     public Nullable<System.Guid> RefRightID { get; set; } 

     public Nullable<int> Priority { get; set; } 

     public bool IsActive { get; set; } 

     public Nullable<bool> IsFunctional { get; set; } 
    } 
} 

--------------------------------- RoleServices.cs --------- ---------------------

using SamarpanInfotech.Core.Paging; 
using SamarpanInfotech.DataModel; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using EntityFramework.Extensions; 
using SamarpanInfotech.Core; 

namespace SamarpanInfotech.Services 
{ 
    public class RoleServices 
    { 
     /// <summary> 
     /// Select All Role 
     /// </summary> 
     /// <param name="pageNumber">Page Number</param> 
     /// <param name="pageRows">Total Number of Rows</param> 
     /// <param name="orderBy">Sort by ascending order and descending order</param> 
     /// <param name="searchtext">Serch from Perticular Text</param> 
     /// <returns>List of All Roles</returns> 
     public PagerList<Role> GetRole(int pageNumber, int pageRows, string orderBy, string searchtext) 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 
       PagerList<Role> paginationObject = null; 
       var query = db.Roles.Where(w => w.IsDelete == false & w.IsDefault == false); 
       if (!string.IsNullOrWhiteSpace(searchtext)) 
       { 
        query = query.Where(w => w.RoleName.Contains(searchtext) || w.RoleCode.Contains(searchtext) || w.AboutRole.Contains(searchtext)); 
       } 
       paginationObject = query.ToPagerListOrderBy(pageNumber, pageRows, orderBy); 
       return paginationObject; 
      } 
     } 
     /// <summary> 
     /// Insert New Role or Edit Existing Role 
     /// </summary> 
     /// <param name="model">Custom Model of Comination of Role and Right Table</param> 
     public void AddEditRoleRight(RoleRightListModel model, Guid? createdBy=null) 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 

       if (model.RoleId == Guid.Empty) 
       { 
        var roleID = Guid.NewGuid(); 
        Role _roles = new Role(); 
        _roles.Id = roleID; 
        _roles.ParentId = db.Roles.FirstOrDefault(m => m.RoleCode == Enums.RoleCode.EMPLOYEE.ToString()).Id; 
        _roles.IsDelete = false; 
        _roles.IsDefault = false; 
        _roles.IsSuperAdmin = false; 
        _roles.CreateDate = DateTime.UtcNow; 
        _roles.CreateBy = createdBy;// ProjectSession.AdminUser.Id; 
        _roles.RoleCode = model.RoleCode; 
        _roles.RoleName = model.RoleName; 
        _roles.AboutRole = model.AboutRole; 
        db.Roles.Add(_roles); 
        db.SaveChanges(); 
        model.RoleId=roleID; 
       } 
       else 
       { 
        db.RoleRights.Where(w => w.FkRoleId == model.RoleId).Delete(); 
        db.Roles.Where(w => w.Id == model.RoleId).Update(u => new Role 
        { 
         RoleCode = model.RoleCode, 
         RoleName = model.RoleName, 
         AboutRole = model.AboutRole 
        }); 
        db.SaveChanges(); 
       } 
       foreach (var _roleright in model.RightModel) 
       { 
        RoleRight newRoleRight = new RoleRight(); 
        newRoleRight.Id = Guid.NewGuid(); 
        newRoleRight.FkRoleId = model.RoleId; 
        newRoleRight.FkRightId = _roleright.RightId; 
        newRoleRight.IsAll = _roleright.IsAllVisible; 
        //if (newRoleRight.IsAll == true) 
        //{ 
        // newRoleRight.IsView = true; 
        // newRoleRight.IsAdd = true; 
        // newRoleRight.IsEdit = true; 
        // newRoleRight.IsDelete = true; 
        //} 
        if (_roleright.IsAddVisible == true || _roleright.IsEditVisible == true || _roleright.IsDeleteVisible == true) 
        { 
         newRoleRight.IsView = true; 
         newRoleRight.IsAdd = _roleright.IsAddVisible; 
         newRoleRight.IsEdit = _roleright.IsEditVisible; 
         newRoleRight.IsDelete = _roleright.IsDeleteVisible; 
        } 
        else 
        { 
         newRoleRight.IsView = _roleright.IsViewVisible; 
         newRoleRight.IsAdd = _roleright.IsAddVisible; 
         newRoleRight.IsEdit = _roleright.IsEditVisible; 
         newRoleRight.IsDelete = _roleright.IsDeleteVisible; 
        } 
        db.RoleRights.Add(newRoleRight); 
        db.SaveChanges(); 
       } 
      } 
     } 
     /// <summary> 
     /// Select Perticular Role by Id 
     /// </summary> 
     /// <param name="Id">Role Id in Role Table</param> 
     /// <returns></returns> 
     public Role GetRoleById(Guid? Id) 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 
       return db.Roles.FirstOrDefault(f => f.Id == Id); 
      } 

     } 
     /// <summary> 
     /// Delete Role By Id 
     /// </summary> 
     /// <param name="Id">Role Id in Role Table</param> 
     public void Delete(Guid Id) 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 
       db.Roles.Where(w => w.Id == Id).Update(u => new Role 
       { 
        IsDelete = true 
       }); 
      } 
     } 
     /// <summary> 
     /// Get All Role List By Id and decending by Created Date 
     /// </summary> 
     /// <returns>All Role list form Role Table decending by Created Date</returns> 
     public List<Role> GetAllRole() 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 
       return db.Roles.Where(w => w.IsDelete == false).OrderByDescending(d => d.CreateDate).ToList(); 
      } 

     } 
     /// <summary> 
     /// Get Rights list from Custom Role Right Model 
     /// </summary> 
     /// <returns>all Rights list from Right table</returns> 
     public List<RightModel> GetRightModel() 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 
       var item = (from r in db.Rights 
          select new RightModel 
          { 
           RightName = r.RightName, 
           IsAllRight = r.IsAll, 
           IsViewRight = r.IsView, 
           IsAddRight = r.IsAdd, 
           IsEditRight = r.IsEdit, 
           IsDeleteRight = r.IsDelete, 
           RightId = r.Id, 
          }).ToList(); 
       return item; 
      } 
     } 
     /// <summary> 
     /// Select Role from Role table and Right from Right table using Custom RoleRightModel 
     /// </summary> 
     /// <param name="Id"></param> 
     /// <returns>List of Combination of Role and Right</returns> 
     public RoleRightListModel GetRoleRightModel(Guid? Id) 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 
       RoleRightListModel model = new RoleRightListModel(); 
       var item = db.Roles.FirstOrDefault(m => m.Id == Id); 
       model.RoleId = item.Id; 
       model.RoleCode = item.RoleCode; 
       model.RoleName = item.RoleName; 
       model.AboutRole = item.AboutRole; 
       model.RightModel = (from r in db.Rights 
            let rr = db.RoleRights.FirstOrDefault(f => f.FkRoleId == model.RoleId & f.FkRightId == r.Id) 
            select new RightModel 
            { 
             IsAllRight = r.IsAll, 
             IsViewRight = r.IsView, 
             IsAddRight = r.IsAdd, 
             IsEditRight = r.IsEdit, 
             IsDeleteRight = r.IsDelete, 
             RightName = r.RightName, 
             RightId = r.Id, 
             IsAllVisible = rr.IsAll ? true : false, 
             IsViewVisible = rr.IsView ? true : false, 
             IsAddVisible = rr.IsAdd ? true : false, 
             IsEditVisible = rr.IsEdit ? true : false, 
             IsDeleteVisible = rr.IsDelete ? true : false, 
            }).ToList(); 
       return model; 
      } 
     } 
     /// <summary> 
     /// Selecting the Rights for Checking intial view,add,edit and delete rights for perticular User(Employee) or Admin 
     /// </summary> 
     /// <param name="Id"></param> 
     /// <returns>List of All Rights value in Right table</returns> 
     public List<RightModel> GetMenuRights(Guid Id) 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 
       RightModel model = new RightModel(); 
       var item = (from r in db.Rights 
          join rr in db.RoleRights on r.Id equals rr.FkRightId 
          where rr.FkRoleId == Id & r.IsActive == true 
          select new RightModel 
          { 
           RightId = r.Id, 
           RightCode = r.RightCode, 
           RightName = r.RightName, 
           MenuName = r.MenuName, 
           Priority = r.Priority, 
           IsActive = r.IsActive, 
           IsFunctional = r.IsFunctional, 
           IsAllRight = r.IsAll, 
           IsViewRight = r.IsView, 
           IsAddRight = r.IsAdd, 
           IsEditRight = r.IsEdit, 
           IsDeleteRight = r.IsDelete, 
           IsAllVisible = rr.IsAll, 
           IsViewVisible = rr.IsView, 
           IsAddVisible = rr.IsAdd, 
           IsEditVisible = rr.IsEdit, 
           IsDeleteVisible = rr.IsDelete, 
           FkRoleId = rr.FkRoleId, 
           RefRightID = rr.FkRightId 
          }).ToList(); 
       return item; 
      } 
     } 

     public List<DropDownModel> GetRoleList() 
     { 
      using (SamarpanInfotechEntities db = new SamarpanInfotechEntities()) 
      { 
       var item = db.Roles.Where(w => w.IsDelete == false & w.IsDefault == false).Select(m => new DropDownModel 
       { 
        Id = m.Id.ToString(), 
        Name = m.RoleName 
       }).ToList(); 
       return item; 
      } 
     } 
    } 
} 

------- ------------------ 사용자 표 ------------------------------ -------- enter image description here

------------------------- 사용자 선택 --------- ------------------------- enter image description here

------------------- ------ 역할 표 --------------------------------------- enter image description here

------------------------- 역할 선택 -------------------- --------------- enter image description here

관련 문제