@Html.TextBoxFor()在相应属性具有值时生成空文本框

时间:2013-11-24 17:55:35

标签: c# asp.net asp.net-mvc razor asp.net-mvc-5

我创建了一个默认的ASP.NET MVC 5项目。

我已向用户添加了FullName属性:

public class ApplicationUser : IdentityUser
{
    public string FullName { get; set; }
}

此属性也添加到viewmodel:

public class ManageUserViewModel
{
    [Display(Name = "Name")]
    public string FullName { get; set; }

    ...
}

在视图上显示文本框:

@Html.TextBoxFor(m => m.FullName)

效果很好,我可以设置用户的FullName。我只有一个问题:如果用户已设置FullName,则文本框仍为空。如何使其具有FullName属性的实际值?

修改

这是使用文本框显示视图的控制器:

    public ActionResult Manage(ManageMessageId? message)
    {
        ViewBag.StatusMessage =
            message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
            : message == ManageMessageId.ChangeDetailsSuccess ? "Your details have been changed."
            : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
            : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
            : message == ManageMessageId.Error ? "An error has occurred."
            : "";
        ViewBag.HasLocalPassword = HasPassword();
        ViewBag.ReturnUrl = Url.Action("Manage");
        return View();
    }

1 个答案:

答案 0 :(得分:1)

您需要1)获取您正在寻找的ApplicationUser,并且2)将该属性绑定到视图模型。

public ActionResult Manage(ManageMessageId? message)
{
    ViewBag.StatusMessage =
        message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
        : message == ManageMessageId.ChangeDetailsSuccess ? "Your details have been changed."
        : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
        : message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
        : message == ManageMessageId.Error ? "An error has occurred."
        : "";
    ViewBag.HasLocalPassword = HasPassword();
    ViewBag.ReturnUrl = Url.Action("Manage");

    // Get the currently logged on user
    var user = UserManager.FindById(User.Identity.GetUserId());

    // Copy the value of FullName to the view model
    var vm = new ManageUserViewModel {
        FullName = user.FullName
    };
    return View(vm);
}