所以我有一个模型,为了简洁起见,删除了其他属性:
public class OutOfLimitReasonViewModel
{
[Required]
public int ReasonId { get; set; }
[Required(ErrorMessage = "Other Reason is required")]
public string OtherReason { get; set; }
}
当然,我在.razor
页面上有一个EditForm
,我关心的InputText
看起来像这样:
<InputText @bind-Value="model.OtherReason" class="form-control" disabled="@(!OtherReasonRequired)" />
<ValidationMessage For="@(() => model.OtherReason)" />
还有一个select
,它具有可用Reason
对象的列表,其中一个是Other
。我确实有一个名为OtherReasonRequired
的属性,它可以图形化地执行我想要的操作(根据是否选择Reason == "Other"
启用或禁用输入(,这样代码就可以工作了:
public bool OtherReasonRequired
{
get
{
var result = false;
if (model.ReasonId > 0)
{
var reason = Reasons.Find(x => x.Id == model.ReasonId);
result = reason.Reason == "Other";
}
return result;
}
}
如果我选择Other
并给OtherReason
一个值,那么保存/提交按钮是有效的,它就可以工作了。
我的问题是当我没有选择Other
时。从图形上看,InputField
确实被禁用并变灰。但是Save/Submit认为模型无效,因为OtherReason
字段中没有值。
我能做些什么让它发挥作用吗?
希望拥有一个名为RequiredIf
的动态属性。
但从逻辑上讲,我认为这是一个错误。如果一个控件被禁用,它的值在我看来是无关紧要的
请检查以下内容。我不使用任何内置的数据注释,但检查输入并让用户知道我希望他们做什么仍然非常容易:
<EditForm Model="@DisplayModel" OnValidSubmit="HandleValidSubmit" >
<InputRadioGroup TValue=int? @bind-Value=DisplayModel.ReasonID>
@for (int i=1; i< Reasons.Count(); i++){
<InputRadio Value=Reasons[i].ID /> @Reasons[i].Description <br/>
}
<InputRadio Value=0 />Other <br/>
</InputRadioGroup>
<input @bind=DisplayModel.OtherText disabled=@((DisplayModel.ReasonID??1) !=0 ) />
<button type="submit">Submit</button>
<div class="text-danger">@DisplayMessage</div>
</EditForm>
@code {
string DisplayMessage="";
class Reason { public int? ID; public string? Description; }
List<Reason> Reasons = new List<Reason> {
new Reason { ID = 0, Description = "Other"},
new Reason { ID = 1, Description = "You're lame" },
new Reason { ID = 2, Description = "I'm too busy" }
};
class MyDisplayModel
{
public int? ReasonID;
public string OtherText="";
}
MyDisplayModel DisplayModel = new MyDisplayModel();
private async Task HandleValidSubmit()
{
if(DisplayModel.ReasonID is not null) if (DisplayModel.ReasonID==0) if (DisplayModel.OtherText == "")
{
DisplayMessage = "You must type a description of your issue.";
StateHasChanged();
await Task.Delay(1500);
DisplayMessage = "";
}
}
}