如何创建用于编辑用户自定义信息的操作和视图?
授权基于 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 表中。
首先,您需要一个用于编辑视图的操作方法。从数据库中获取用户并构建 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);
}
现在它只是在你看来编码。我的看起来像这样:
@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 可能会有所帮助。此解决方案编辑当前登录的用户,但添加用户名作为操作参数相当简单。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)