【问题标题】:Avoid hardcoded strings in UrlHelper.Action and ModelState.AddModelError避免在 UrlHelper.Action 和 ModelState.AddModelError 中使用硬编码字符串
【发布时间】:2013-03-21 14:26:47
【问题描述】:

我有以下代码行:

return Json(new { redirectTo = UrlHelper.Action("Index", "Home") });

ModelState.AddModelError("Useraccount.Email", emailAlreadyExistsException.Message);

对于 UrlHelper.Action 方法和 ModelState.AddModelError 方法,我想避免硬编码字符串。还有更好的可能吗?

【问题讨论】:

  • 我希望我可以为 UrlHelper.Action 使用类似 RedirectToRouteResult 的东西。

标签: asp.net-mvc asp.net-mvc-3 modelstate urlhelper


【解决方案1】:

您可以创建一个常量文件并改用常量:

public static class Constants 
{
    public const string HomeController = "Home";
    public const string IndexAction = "Index";
    public const string UserAccountEmail = "Useraccount.Email";
}

然后你的代码变成:

return Json(new { redirectTo = UrlHelper.Action(Constants.IndexAction, Constants.HomeController) });

ModelState.AddModelError(Constants.UserAccountEmail, emailAlreadyExistsException.Message);

作为验证的替代方法,您可以使用像 FluentValidation 这样的库

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    相关资源
    最近更新 更多