Asp.net mvc MVC中的模型状态验证
该类有一个属性Asp.net mvc MVC中的模型状态验证,asp.net-mvc,entity-framework,modelstate,actionfilterattribute,Asp.net Mvc,Entity Framework,Modelstate,Actionfilterattribute,该类有一个属性UserId,该属性是ApplicationUser的类型及其必需属性,当然,由于安全原因,我们无法将其从视图传递到控制器 现在,当控制器检查模型的状态时,模型的状态不正确,因为没有UserId值,它返回视图,如果我使用视图模型,该类有50多个属性,并将值从视图模型分配给类,然后保存它,那么保存编辑等操作非常繁琐和困难,从这个问题中可以得到什么建议 谢谢您可以使用自动绑定属性 假设我们有model.UserId=123,actionParams); //假设您知道在这里获取user
UserId
,该属性是ApplicationUser
的类型及其必需属性,当然,由于安全原因,我们无法将其从视图传递到控制器
现在,当控制器检查模型的状态时,模型的状态不正确,因为没有UserId值,它返回视图,如果我使用视图模型,该类有50多个属性,并将值从视图模型分配给类,然后保存它,那么保存编辑等操作非常繁琐和困难,从这个问题中可以得到什么建议
谢谢您可以使用自动绑定属性
假设我们有
和用户ID
属性
public interface IAutoBindingUserId
{
int UserId { get; set; }
}
public class UserSettingMetaModel : IAutoBindingUserId
{
public int Id { get; set; }
[Required]
public int UserId { get; set; }
// The rest of properties
}
在用户设置控制器中,我们有
[HttpPost]
[AutoBindProperty]
public JsonResult Add(UserSettingMetaModel metaModel)
{
if (ModelState.IsValid)
{
// do something
}
}
在自动绑定属性的感觉背后
[AttributeUsage(AttributeTargets.Method)]
public sealed class AutoBindPropertyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var actionParams = filterContext.ActionParameters.Values.FirstOrDefault();
Bind<IAutoBindingUserId>(model => model.UserId = 123, actionParams);
// Assuming that you know the way get userId value here.
}
private static void Bind<T>(Action<T> doBinding, object actionParams) where T : class
{
if (actionParams is T model)
{
doBinding(model);
}
}
}
[AttributeUsage(AttributeTargets.Method)]
公共密封类AutoBindPropertyAttribute:ActionFilterAttribute
{
公共覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
{
var actionParams=filterContext.ActionParameters.Values.FirstOrDefault();
绑定(model=>model.UserId=123,actionParams);
//假设您知道在这里获取userId值的方法。
}
私有静态void绑定(Action-doBinding,object-actionParams),其中T:class
{
if(actionParams为T型)
{
多绑定(模型);
}
}
}
无论如何,感谢您的合作解决了这个问题
我发现的从类返回用户id的最简单方法是,在类构造函数中只需要一行代码
public constructor()
{
UserId = ClaimsPrincipal.Current.Identity.GetUserId();
}
你在用ASPNET MVC吗?@Phong是的,我在用MVC@Mohammad这回答了你的问题吗?如果你需要帮助,请告诉我?别忘了投我一票,我的回答对你很有用!