如何创建用于编辑用户自定义信息的 Action 和 View ?
授权基于 VS 使用 MVC 4 项目创建的成员资格。
我已经添加了额外的列,例如 FirstName 等。我需要并且注册工作正常,但我不知道如何让这个属性显示在 @Html.EditorFor
和将更改保存在数据库中(表 UserProfile)。
非常感谢您的每一个提示。
为版本创建模型:
public class UserProfileEdit
{
[Required]
[Display(Name = "First name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
最佳答案
所以你想要一个编辑页面来编辑用户的个人信息。其他列已添加到 UserProfile 表中。
首先,您需要一个用于编辑 View 的操作方法。从数据库中获取用户并构建您的 UserProfileEdit 模型。
public ActionResult Edit()
{
string username = User.Identity.Name;
// Fetch the userprofile
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.Equals(username));
// Construct the viewmodel
UserProfileEdit model = new UserProfileEdit();
model.FirstName = user.FirstName;
model.LastName = user.LastName;
model.Email = user.Email;
return View(model);
}
当我们发布编辑表单时,我们发布了 UserProfileEdit 模型。我们再次从数据库中获取 UserProfile 并更改发布的字段。
[HttpPost]
public ActionResult Edit(UserProfileEdit userprofile)
{
if (ModelState.IsValid)
{
string username = User.Identity.Name;
// Get the userprofile
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.Equals(username));
// Update fields
user.FirstName = userprofile.FirstName;
user.LastName = userprofile.LastName;
user.Email = userprofile.Email;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index", "Home"); // or whatever
}
return View(userprofile);
}
现在它只是在您的 View 中编码。我的看起来像这样:
@model UserProfileEdit
@using (Html.BeginForm("Edit", "Account"))
{
@Html.EditorFor(model => model.FirstName)
@Html.EditorFor(model => model.LastName)
@Html.EditorFor(model => model.Email)
<input type="submit" value="Save" />
}
如果您的编辑模型有大量字段,Automapper 可能会有所帮助。此解决方案编辑当前登录的用户,但添加用户名作为操作参数相当简单。
关于asp.net-mvc - 编辑用户个人资料详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22955872/