我正在使用UserProfile编辑页面,其中只能编辑UserProfile模型的字段子集。许多字段只能对具有特殊角色的用户进行编辑,并且字段UserName当然是不可编辑且隐藏的。如何在回发后维护模型值而不暴露它们
现在我想包括hiddenfields为所有不被用户编辑的字段,以及装饰我的模式是这样的:代码
[Table("UserProfile")]
public partial class UserProfile
{
public UserProfile()
{
webpages_Roles = new HashSet<Role>();
}
[Key]
public int UserId { get; set; }
[Required]
[StringLength(56)]
[Display(Name="Email")]
[Editable(false)] // is this the way to go?
public string UserName { get; set; }
[Required]
[Display(Name = "First name")]
[StringLength(256)]
public string FirstName { get; set; }
[Editable(false)] // is this the way to go?
public bool SomeSetting { get; set; }
// ... more properties are unimportant for this example
}
其他相关位:
//
// GET: /Account/Profile
public ActionResult UserProfile()
{
var userProfile = db.UserProfiles.Find(WebSecurity.CurrentUserId);
return View(userProfile);
}
//
// POST: /Account/Profile
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult UserProfile(UserProfile model)
{
// if I dont include UserName, validation will fail since it
// is now null and the field is [Required]
if (ModelState.IsValid)
{
// if I dont include hidden fields, UserId, UserName
// and SomeSetting will be null here
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
}
return View(model);
}
相关视图代码:
@Html.HiddenFor(m => m.UserId)
@Html.HiddenFor(m => m.UserName)
@Html.HiddenFor(m => m.SomeSetting)
不过,我很担心这些暴露通过隐藏输入字段。不管聪明还是恶意用户都无法编辑它们?我明白,我必须包括他们,否则在回传后属性将为null
。有人能够启发我吗?
可以使用_viewmodel_,并与您_model_ – 2014-09-05 15:19:43
'地图也不会聪明或恶意用户能够反正编辑'是的,你应该验证在回发或Si的作用? milar。你可以使用'ViewModel'并根据角色设置单独的属性,而不是整个实体。 – Jonesopolis 2014-09-05 15:20:17
@Jonesy听起来不错。 ViewModel和Model之间的映射最简单的方法是什么? AutoMapper?还是有更简单的方法? – Korijn 2014-09-05 16:15:25