自定义模型绑定MVC
我想将JSON对象的列表传递给控制器方法,并自动在控制器中定义并填充正确的类型。自定义模型绑定MVC
JSON发布到控制器:
{ Type : 'Image', ImageName : 'blah.jpg' },
{ Type : 'Text', Text: 'Hello', Font: 'Some Font' }..
控制器:
public ActionResult SaveCOntent(IList<Item> content)
所以我的印象已经有了,是我需要使用ModelBinding的元素转化为正确的类型。我试着按照另一个建议的帖子(http://*.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);
}
现在能正常工作的第一类(链接),但只要我尝试的图像做同样的我得到一个错误说明
具有相同密钥的项目已被添加。
原来,它工作正常,我的问题是这个对象的基类有一个属性具有相同的名称。
---------------- Data Model - > Custom Folder - > 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; }
}
}
---------------- Data Model - > Custom Folder - > 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;
}
}
}
}
------- ------------------用户表------------------------------ --------
-------------------------用户选择--------- -------------------------
------------------- ------角色表---------------------------------------
-------------------------角色选择-------------------- ---------------
我fou找出导致相同键错误的原因,基本上有两个属性在继承的不同级别具有相同的名称。 不知道是否有更好的方法来做到这一点? – BenW 2012-08-02 12:38:32