【问题标题】:display ap.net web api returned result to mvc view显示 ap.net web api 返回的结果到 mvc 视图
【发布时间】:2016-06-22 03:28:15
【问题描述】:

我使用 mvc 项目和 web api 单独的项目创建了一个 web 应用程序,我使用身份来注册用户。 我的问题是当 web api 返回结果时如何在 MVC 视图中显示它

这是我的 web api 控制器 -

    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);



        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

    }

这就是我如何调用这个 web api -

    public async Task<ActionResult> Register(RegisterView model)
    {
        //
        HttpClient client = new HttpClient();
        //The URL of the WEB API Service
        string url = "http://localhost:51493/Api/Account/Register";
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //

        HttpResponseMessage responseMessage = await client.PostAsJsonAsync(url, model);
        if (responseMessage.IsSuccessStatusCode)
        {
            return RedirectToAction("Index");
        }

        else{//pass the validation errors in view and display it in view}
    }
}

如何做到这一点?

【问题讨论】:

  • 您将 Web api 调用的结果作为模型或模型的一部分传递给您要在其中显示它的视图。它与使用任何其他外部数据块没有什么不同你想在你的视图中显示。不同的是,您也应该能够使用客户端代码访问 Web API 而不是返回服务器来完成此操作。
  • 你能否在代码的帮助下详细说明我是一个 .net 框架的初学者,谢谢 :)
  • 那么我建议你阅读一些关于 MVC 工作原理以及如何在视图中显示数据的教程或书籍。

标签: .net model-view-controller asp.net-web-api


【解决方案1】:

去掉else,没必要。

添加

return View(model);

另外,在您的视图中启用不显眼的验证

【讨论】:

  • @alez ovechkin 如何将返回的 web api 响应消息与模型一起传递给视图(模型);声明
  • 您可以在 ModelState.AddError() 中使用您的响应
  • 感谢@Alex,现在我在我看来是验证错误,但它看起来像这样 {"Message":"The request is invalid.","ModelState":{"":["Name haseeb @yahoo.com 已被占用。","Email 'haseeb@yahoo.com' 已被占用。"]}} 我怎样才能只显示消息 i-e name haseeb@yahoo.com is already taken nothing else and errors should be显示在验证失败的第一个文本框的正上方
  • 我猜你应该只传递 ModelState,而不是“请求无效”。您可以反序列化响应,仅获取 ModelState 并将其传递给您的视图
猜你喜欢
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
  • 2016-03-22
  • 2021-06-21
  • 1970-01-01
相关资源
最近更新 更多