c# - 如何在 xamarin 表单中显示模型错误表单 web api
问题描述
我有一个 web api、mvc 网站和 xamarin 表单应用程序(android 和 ios)。我还有一个类库来与我的解决方案中的 api 进行通信。我已经成功地让所有这些都工作了,但是我在 xamarin 表单应用程序中遇到了模型错误。在 mvc 网站中,我有以下代码来解码模型错误,当它失败时我将响应传递给它。
protected void AddResponseErrorsToModelState(ApiResponse response)
{
System.Collections.Generic.IDictionary<string, string[]> errors = response.ErrorState.ModelState;
if (errors == null)
{
TempData["ERR"] = "An unexpected error occured.";
return;
}
foreach (System.Collections.Generic.KeyValuePair<string, string[]> error in errors)
{
// add model error for empty keys
if (string.IsNullOrEmpty(error.Key))
{
ModelState.AddModelError("", error.Value[0]);
}
// add model properties errors
foreach (System.Collections.Generic.KeyValuePair<string, ModelState> entry in
from entry in ModelState
let matchSuffix = string.Concat(".", entry.Key)
where error.Key.EndsWith(matchSuffix)
select entry)
{
ModelState.AddModelError(entry.Key, error.Value[0]);
}
}
}
然后错误只是在下面的行中显示在视图中。
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
现在的问题是我不知道如何在 xamarin 表单应用程序中显示这些模型错误。我已经能够将视图模型绑定到页面:
BindingContext = new RegisterModel();
我用这个提交模型:
public Command RegisterCommand => new Command(async () =>
{
var response = await loginClient.Register(this);
if (response.StatusIsSuccessful)
{
// go login page
string message = "Registration successful, login to continue.";
await Shell.Current.GoToAsync($"login?message={message}");
}
else
{
await Application.Current.MainPage.DisplayAlert("Error", "An error occured", "Try Again");
}
});
当出现错误时,如何在页面中显示错误,就像我在 mvc 网站中所做的那样,请帮助我。
解决方案
推荐阅读
- javascript - NodeJS - 将 event.headers 转换为小写以用于 AWS
- c# - 禁用 eazfuscator json 加密
- c++ - 在 QT 小部件表单应用程序中打印调试信息
- php - Laravel 在通知邮件中添加密件抄送
- php - 括号在 PHP 代码中丢失
- mysql - 为什么 mysql innodb 表中的记录值被意外替换?
- python-social-auth - 当我从 django 1.8 更新到 1.11.13 关系“social_auth_usersocialauth”不存在时出现错误
- mysql - mysql。我想替换列中某些值的名称
- ios - tvos 如何始终关注特定的 tableViewCell
- reactjs - React Input 组件单元测试值始终未定义