这段代码在我同事的机器上运行正常,但是当我在我的机器上运行此代码时,它给出了“错误没有为此对象定义的无参数构造函数”。如果我添加无参数构造函数它适用于我,但你在下面的代码public ActionResult User_Read([DataSourceRequest] DataSourceRequest request)
中看到,然后它们给我错误“对象引用没有设置为对象的实例。”在这个街区。
return Json(repository.All()
.Select(s => new UserViewModel()
{
Id = s.Id,
UserName = s.UserName,
Email = s.Email,
RoleId = s.Role,
Locked = s.Locked,
CreatedAt = s.CreatedAt,
UpdatedAt = s.UpdatedAt
}).ToDataSourceResult(request));
using Kendo.Mvc.UI;
using MHUSA.Pricing.Core.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using MHUSAPricingRI.WebUI.Models;
using MHUSA.Pricing.Core;
namespace MHUSAPricingRI.WebUI.Controllers
{
public class UserController : Controller
{
private readonly IUserRepository repository;
//public UserController() { }
public UserController(IUserRepository userRepository)
{
this.repository = userRepository;
}
public ActionResult Index()
{
PopulateRoles();
return View();
}
public ActionResult User_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(repository.All()
.Select(s => new UserViewModel()
{
Id = s.Id,
UserName = s.UserName,
Email = s.Email,
RoleId = s.Role,
Locked = s.Locked,
CreatedAt = s.CreatedAt,
UpdatedAt = s.UpdatedAt
})
.ToDataSourceResult(request));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult User_Create([DataSourceRequest] DataSourceRequest request, [Bind(Exclude = "Id")] UserViewModel user)
{
if (user != null && ModelState.IsValid)
{
User target = repository.FindOne(u => u.UserName == user.UserName);
if (target == null)
{
target = new User(user.UserName, "password", user.Email, (Role) user.RoleId);
if (user.Locked)
{
target.Lock();
}
repository.Save(target);
}
}
return Json(new[] { user }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult User_Update([DataSourceRequest] DataSourceRequest request, UserViewModel user)
{
if (user != null && ModelState.IsValid)
{
User target = repository.FindOne(u => u.Id == user.Id);
if (target != null)
{
//target.Password = user.Password;
target.Email = user.Email;
target.Role = user.RoleId;
target.UpdatedAt = DateTime.UtcNow;
if (user.Locked)
{
target.Lock();
}
else
{
target.Unlock();
}
repository.Save(target);
}
}
return Json(new[] { user }.ToDataSourceResult(request, ModelState));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult User_Destroy([DataSourceRequest] DataSourceRequest request, UserViewModel user)
{
if (user != null)
{
User target = repository.FindOne(u => u.Id == user.Id);
repository.Remove(target);
}
return Json(ModelState.ToDataSourceResult());
}
private void PopulateRoles()
{
List<UserRoleViewModel> userRoleList = new List<UserRoleViewModel>();
string[] roles = Enum.GetNames(typeof(Role));
for (int i = 0; i < roles.Length; i++)
{
userRoleList.Add(new UserRoleViewModel
{
RoleId = i,
RoleName = roles[i]
});
}
ViewData["roles"] = userRoleList.ToList();
}
}
}