asp.net - 从 MVC2 模型的属性获取 DisplayName 属性

标签 asp.net asp.net-mvc-2 attributes

所以,我的 MVC 2 应用程序中有一个联系表单。

我想以编程方式通过电子邮件发送“ContactModel”的所有属性。

这是我想在伪代码中执行的操作:

[HttpPost]
public ActionResult Contact(ContactModel model)
    if(!ModelState.IsValid){
        TempData["errorMessage"] = "You are a failure!";
        return View(model);
    }
    else{
        var htmlMessage = new StringBuilder("<table>");
        const string templateRow = "<tr><td>{0}: </td><td><strong>{1}</strong></td></tr>";

        /* ************************************************* */
        /* This is the part I need some serious help with... */
        /* ************************************************* */
        foreach(var property in someEnumerableObjectBasedOnMyModel){
            htmlMessage.AppendFormat(templateRow,
                // the display name for the property
                property.GetDisplayName(),
                // the value the user input for the property (HTMLEncoded)
                model[property.Key]
            );
        }
        /* ************************************************* */

        htmlMessage.Append("</table>");

        // send the message...
        SomeMagicalEmailer.Send("to@example.com", "from@example.com", "Subject of Message ", htmlMessage.ToString() );
        TempData["message"] = "You are awesome!";
        return RedirectToAction("Contact", "Home");
    }
}

以防万一...ContactModel 设置 DisplayName 属性,如下所示:

[DisplayName("First Name")]
public string FirstName {get; set ;}

我想通过不重复 DisplayName 名称来保持简洁。

具体来说,我想枚举 ContactModel 中的每个属性,获取其 DisplayName,并获取其提交的值。

最佳答案

您需要对对象的属性及其自定义属性使用反射来获取其名称/值对。

foreach (var property in typeof(ContactModel).GetProperties())
{
     var attribute = property.GetCustomAttributes(typeof(DisplayNameAttribute),false)
                             .Cast<DisplayNameAttribute>()
                             .FirstOrDefault();
     if (attribute != null)
     {
          var value = property.GetValue( model, null );
          var name = attribute.DisplayName;

          htmlMessage.AppendFormat( templateRow, name, value );
     }
}

关于asp.net - 从 MVC2 模型的属性获取 DisplayName 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4547940/

相关文章:

asp.net - 如何让搜索引擎抓取我网站上万个页面

php - 选择哪种解决方案以获得更好的性能?为什么?

asp.net - 上传前设置文件路径和名称属性

php - Magento升级脚本不升级

grails - 我们可以为 grails 中的域类属性设置多个别名吗

asp.net - 如何使用 MS 网络监视器捕获对 IIS 和 Tomcat 的传入请求

asp.net-mvc - ASP.NET MVC 2 VirtualPathProvider GetFile 每次请求

Apache 在运行 mod_mono 时泄漏信号量

asp.net-mvc - 如果我使用ASP .NET MVC 3,可以安全地从Visual Studio中删除ASP .NET MVC 2吗?

python - 为什么属性在 Python 中跨类继承?