首页 > 解决方案 > 如何在 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 网站中所做的那样,请帮助我。

标签: c#xamlasp.net-web-apixamarin.formsmvvm

解决方案


推荐阅读