Skip to main content
 首页 » 编程设计

c#之渲染 LabelFor 不显示覆盖的 getter 函数

2024年02月13日9lovecherry

如果这是一个菜鸟问题,请原谅我,但我已经在 SO、谷歌上进行了搜索,并花了一个多小时阅读了一本 ASP.NET MVC 4 PRO 书籍,阅读了有关渲染强类型助手等内容。我才刚刚开始学习 ASP。 NET 4 MVC 所以请放轻松。

我有一个名为 USER 的模型类和一个名为 Name 的属性,带有覆盖的 getter 和 setter(我这样调用它,我不确定这是不是正确命名)

//using... 
 
namespace MvcMyApplication1.Models 
{ 
    public class User 
    { 
        [ScaffoldColumn(false)] 
        public int Id { get; set; } 
        public string Name 
        { 
            get 
            { 
                return WindowsIdentity.GetCurrent().Name.Split('\\')[1]; 
            } 
            set 
            { 
                Name = WindowsIdentity.GetCurrent().Name.Split('\\')[1]; 
            } 
        } 
        [Required(ErrorMessage="Password is required")] 
        public string Password { get; set; } 
    } 
} 

所以,在我的 View 中,我试图显示 get 函数的结果,但我迷路了,不知道该怎么做。

@using(Html.BeginForm()) 
{ 
    @Html.ValidationSummary(excludePropertyErrors: true); 
    // changed from LabelFor to DisplayFor 
    @Html.DisplayFor(m => m.Name)<br /> 
    @Html.PasswordFor(m => m.Password)<br /> 
    <input type="submit" value="Log in" /> 
} 

我尝试添加属性,但我不确定如何将 Name= 分配给 get 函数

  [DisplayName(Name="I want to call the get function here")] 
  public string Name { get; set; } 

在我的 Controller 中我有这段代码:

[HttpGet] 
        public ActionResult Index() 
        { 
            User newUser = new User(); 
            return View(); 
        } 
 
        [HttpPost] 
        public ActionResult Index(User m) 
        { 
            if (ModelState.IsValid) 
            { 
                return View("Report", m); 
            } 
            { 
                return View(m); 
            } 
        } 

这会转到 Report View 通常显示 Windows 登录名

@using (Html.BeginForm()) 
{ 
@Html.DisplayForModel() 
} 

编辑:
在将 LabelFor 与 DisplayFor 交换后,将呈现 Windows 登录,但仅在单击 log 之后在 按钮中。我第一次打开页面时它没有呈现

请您参考如下方法:

您没有将模型传递给初始 View :

return View(); 

应该是

return View(newUser);