[英]Improve nameof() in C#
我正在使用带有 C# 的 ASP.NET Core MVC。
我这样定义我的模型:
public class Student
{
public class FirstName {get;set;}
public int? PriorityId { get; set; }
}
public class Priority
{
[Key]
public int PriorityId { get; set; }
[Required]
[Display(Name = "Priority Name")]
public string Name { get; set; }
}
所以它会像这样为优先级下拉列表呈现 HTML。
<div class="col-sm-4">
<div class="form-group">
<label for="Student_PriorityId">Priority<span style="color:red"> *</span></label>
<select class="form-control valid" id="Student_PriorityId" name="Student.PriorityId" aria-invalid="false">
<option selected="selected" value="0">Select</option>
<option value="3">High</option>
<option value="1">Low</option>
<option value="2">Medium</option>
</select>
<span class="text-danger field-validation-error" data-valmsg-for="Student.PriorityId" data-valmsg-replace="true">Priority is required.</span>
</div>
</div>
问题
当我要检查自定义验证时,消息不会显示在下拉列表下方。
if (obj.Student.PriorityId <= 0)
{
ModelState.AddModelError(nameof(obj.Student.PriorityId), "Priority is required.");
}
当我尝试使用nameof()
时,上面的代码不起作用。
但是当我删除nameof()
并写下如下字符串时。 它在下拉成功显示我的错误消息。
if (obj.Student.PriorityId <= 0)
{
ModelState.AddModelError("Student.PriorityId", "Priority is required.");
}
有什么方法可以改进 C# 的nameof()
函数吗?
我不确定这是一种改进,但您可以编写如下方法:
public static string NameOf<T>(Expression<Func<T>> func)
{
return string.Join(".", func.ToString().Split('.').Reverse().Take(3).Reverse().ToArray());
}
那么你的代码将是
if (obj.Student.PriorityId <= 0)
{
ModelState.AddModelError(NameOf( () => obj.Student.PriorityId ), "Priority is required.");
}
在这种情况下, NameOf
将返回“obj.Student.PriorityId”。
这是一个如何使用CallerArgumentExpressionAttribute
代替nameof
的示例。
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Runtime.CompilerServices;
public static class ModelStateExtensions
{
public static void AddModelErrorEx(
this ModelStateDictionary modelStateDictionary,
object _,
string errorMessage,
[CallerArgumentExpression("_")] string expr = "")
=> modelStateDictionary.AddModelError(expr, errorMessage);
}
用法:
// Argument 'expr' will be "Student.PriorityId" here.
ModelState.AddModelErrorEx(Student.PriorityId, "Priority is required.")
// Argument 'expr' will be "obj.Student.PriorityId" here.
ModelState.AddModelErrorEx(obj.Student.PriorityId, "Priority is required.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.