[英].NET Core View property name different from model property name
I have an ajax function that returns an error message to a field when an error occurs serverside.我有一个 ajax 函数,当服务器端发生错误时,它会向字段返回错误消息。
This is how I show my errors:这是我显示错误的方式:
$.each(result.errors, function (index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
element.empty();
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
This is supposed to read the returned propertyname which is the name of my field and display the message on it.这应该读取返回的 propertyname,它是我的字段的名称并在其上显示消息。
This is the field.这是场。 It is a dropdownlist
这是一个下拉列表
<div class="row">
<div class="col-sm-12">
<div class="form-group">
@Html.HiddenFor(m => m.UserId)
@Html.DropDownListFor(m => m.BranchDropdownListViewModel.BranchId, Model.BranchDropdownListViewModel.Branch, "Select Branch", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.BranchDropdownListViewModel.BranchId)
</div>
</div>
</div>
When I inspect the code, the name of this dropdown is BranchDropdownListViewModel.BranchId当我检查代码时,此下拉列表的名称是 BranchDropdownListViewModel.BranchId
However, in my controller when I try to find the name of this field like this:但是,在我的控制器中,当我尝试像这样查找此字段的名称时:
ModelState.AddModelError(nameof(Input.BranchDropdownListViewModel.BranchId), "Branch already exists");
It shows BranchId as the name of the field only.它仅将 BranchId 显示为字段名称。
This is the model:这是模型:
public class UserBranchDetailsViewModel
{
public string Id { get; set; }
public string UserId { get; set; }
public string TenantId { get; set; }
public BranchDropdownListViewModel BranchDropdownListViewModel { get; set; }
}
public class BranchDropdownListViewModel
{
[Required]
[Display(Name = "Branch")]
public string BranchId { get; set; }
public IEnumerable<SelectListItem> Branch { get; set; }
}
How can I match the name shown in the view from the controller?如何匹配控制器视图中显示的名称? Must I do it manually?
我必须手动完成吗?
The use of the nameof would only produce the last part of the property name, which in your case is BranchId
.使用 nameof 只会产生属性名称的最后一部分,在您的情况下是
BranchId
。
Since getting an injected HtmlHelper
is not so straightforward, I would suggest you to do由于获得注入的
HtmlHelper
不是那么简单,我建议您这样做
ModelState.AddModelError($"{nameof(Input.BranchDropdownListViewModel)}.{nameof(Input.BranchDropdownListViewModel.BranchId)}", "Branch already exists");
But if you really want to use the HtmlHelper
, look at this method HtmlHelper.NameFor()
.但是如果你真的想使用
HtmlHelper
,看看这个方法HtmlHelper.NameFor()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.