Asp.net mvc 5 如何使用User.Identity.GetUserId()使模型状态有效?

Asp.net mvc 5 如何使用User.Identity.GetUserId()使模型状态有效?,asp.net-mvc-5,asp.net-identity,modelstate,Asp.net Mvc 5,Asp.net Identity,Modelstate,我想跟踪整个应用程序中发生的每个事务,因为我正在使用“user.Identity.GetUserId();”保存loggedin user的用户id,但我无法在视图中分配用户id,因为它是公共的。正在尝试从控制器保存该id 域模型 公共类DemoForIdentity { [关键] 公共字符串Id{get;set;} 公共字符串地址{get;set;} } 控制器 [HttpPost] [ValidateAntiForgeryToken] //公共操作结果创建([Bind(Include=“I

我想跟踪整个应用程序中发生的每个事务,因为我正在使用“user.Identity.GetUserId();”保存loggedin user的用户id,但我无法在视图中分配用户id,因为它是公共的。正在尝试从控制器保存该id

域模型

公共类DemoForIdentity
{
[关键]
公共字符串Id{get;set;}
公共字符串地址{get;set;}
}
控制器

[HttpPost]
[ValidateAntiForgeryToken]
//公共操作结果创建([Bind(Include=“Id,Address”)]DemoForIdentity DemoForIdentity)
公共操作结果创建([Bind(Include=“Address”)]DemoForIdentity DemoForIdentity)
{
demoForIdentity.Id=User.Identity.GetUserId();
//模型状态在此将无效。
//我无法从viewmodel中访问User.Identity.GetUserId(),无法设置隐藏字段的值
if(ModelState.IsValid)
{
db.demoForIdentity.Add(demoForIdentity);
db.SaveChanges();
返回操作(“索引”);
}
返回视图(demoForIdentity);
}
看法

@model Try.Models.DemoForIdentity
....
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
民主身份

@Html.ValidationSummary(true,“,new{@class=“text danger”}) // //@Html.LabelFor(model=>model.Id,htmlAttributes:new{@class=“controllabel col-md-2”}) // //@Html.EditorFor(model=>model.Id,new{htmlAttributes=new{@class=“form control”}) //@Html.ValidationMessageFor(model=>model.Id,“,new{@class=“text danger”}) // // @LabelFor(model=>model.Address,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Address,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Address,“,new{@class=“text danger”}) }
我已经从视图中注释了id


每次保存用户ID最安全的方法是什么

不要在视图中使用数据模型。创建视图模型。是什么让您认为需要在视图中包含隐藏字段?在POST方法中,您只需使用
User.Identity.GetUserId()
Yup获得它,我将使用视图模型。当我尝试在post方法中使用GetuserId时,如果modelstate.isvalid的循环有效,它不会执行。当我改变模型状态时。你不能改变
ModelState
!而且您的属性上甚至没有任何验证属性,因此
ModelState
永远不会无效。如果是的话,那是因为你没有给我们看代码。对不起,我好像很困惑或者搞砸了。“demoForIdentity.Id=User.Identity.GetUserId();”此时,我正在更改模型状态。您正在更改模型中属性的值。您没有更改
ModelState
请勿在视图中使用数据模型。创建视图模型。是什么让您认为需要在视图中包含隐藏字段?在POST方法中,您只需使用
User.Identity.GetUserId()
Yup获得它,我将使用视图模型。当我尝试在post方法中使用GetuserId时,如果modelstate.isvalid的循环有效,它不会执行。当我改变模型状态时。你不能改变
ModelState
!而且您的属性上甚至没有任何验证属性,因此
ModelState
永远不会无效。如果是的话,那是因为你没有给我们看代码。对不起,我好像很困惑或者搞砸了。“demoForIdentity.Id=User.Identity.GetUserId();”此时,我正在更改模型状态。您正在更改模型中属性的值。您没有更改
ModelState