【问题标题】:Xamarin How to load listView detail from Rest API based on id?Xamarin 如何根据 id 从 Rest API 加载 listView 详细信息?
【发布时间】:2020-02-26 16:33:28
【问题描述】:

我有列表视图。单击该项目时,它将打开详细信息页面。但是对于性能问题,在restAPI中我将它设置为只发送listView上需要的数据。这就是为什么我想从单击的列表视图中获得对基于 api 的 id 的新请求。

listview.xaml.cs:

        private async void OnItemSelected(object sender, ItemTappedEventArgs e)
        {
        var itemDetail = e.Item as Data.Models.ModelAttendance.Attendance;
        await Navigation.PushAsync(new ListDetailAttendPage
            (
                itemDetail.Id, itemDetail.Image, itemDetail.Created, itemDetail.AddressDetail,
                itemDetail.Note, itemDetail.Activity
            ));
        }

listViewDetail.xaml.cs

    private ObservableCollection<Data.Models.ModelAttendance.Attendance> _attendances;

    public ListDetailAttendPage (long id, byte[] image, DateTime created, string addressDetail, string note, string activity)
    {
        InitializeComponent ();

        long idItem = id;
        ImgSelfie.Source = ImageSource.FromStream(() => new MemoryStream(image));
        EntTime.Text = created.ToString();
        EdtLocation.Text = addressDetail;
        EntNote.Text = note;
        LblAction.Text = activity;

    }

    protected override void OnAppearing()
    {
        _attendances = new ObservableCollection<Data.Models.ModelAttendance.Attendance>();
        base.OnAppearing();
    }

我在列表视图页面中使用的 API 代码:

    [HttpGet]
    public IActionResult GetM_ATTENDANCE()
    {
        var data = _context.M_ATTENDANCE.Select(f => new Attendance
        {
            Id = f.Id,
            Name = f.Name,
            Activity = f.Activity,
            Created = f.Created
        }).OrderByDescending(x => x.Id).ToList();

        var tempJson = new
        {
            Data = data,
            Size = data.Count
        };
        return Json(tempJson);
    }

如何在 xamarin.form 中做到这一点?我已经搜索过,但没有正确的解决方案。这是我尝试过的,但我仍然无法获得想要的数据:

    private ObservableCollection<Data.Models.ModelAttendance.Attendance> _attendances;
    HttpClient client = new HttpClient();

    public ListDetailAttendPage (long id, byte[] image, DateTime created, string addressDetail, string note, string activity)
    {
        InitializeComponent ();

        long idItem = id;
        ImgSelfie.Source = ImageSource.FromStream(() => new MemoryStream(image));
        EntTime.Text = created.ToString();
        EdtLocation.Text = addressDetail;
        EntNote.Text = note;
        LblAction.Text = activity;

        Task.Run(async () =>
        {
            await GetItem(idItem);
        });

    }

    async Task GetItem(long id)
    {
        HttpResponseMessage message = await client.GetAsync(string.Format("http://[url]:[port]/api/attendances/" + id));
        string jsonString = await message.Content.ReadAsStringAsync();

     //what should I do next to get the data here?

    }

    protected override void OnAppearing()
    {
        _attendances = new ObservableCollection<Data.Models.ModelAttendance.Attendance>();
        base.OnAppearing();
    }

我已经有了基于 id 获取响应的 rest API,但不知道在 Xamarin 中使用它:

        // GET: api/Attendances/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetAttendance(long id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var attendance = await _context.M_ATTENDANCE.FindAsync(id);

        if (attendance == null)
        {
            return NotFound();
        }

        return Ok(attendance);
    }

我刚开始学习xamarin,如果我的问题还不清楚,请问我

非常感谢您的帮助^_^

【问题讨论】:

  • 你需要将jsonString反序列化为一个对象。
  • 你能在这里分享jsonString吗?只需要一个例子。
  • 这是你的意思吗? @杰森var result = JsonConvert.DeserializeObject(jsonString);
  • 我的意思是this
  • 您如何获取列表视图的数据?流程应该基本一样

标签: c# entity-framework asp.net-core xamarin.forms mvvmcross


【解决方案1】:

只需将JSON string反序列化到Model类中

using Newtonsoft.Json;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();


        testAsync();
    }

    public async Task testAsync() {

        string json = @"{
              'id': '123',
              'name': 'User name',
              'nik': '213123'
            }";

        Model m = JsonConvert.DeserializeObject<Model>(json);

        Console.WriteLine(m.name);
        Console.WriteLine(m.nik);

    }
}

public class Model
{
    public string id { get; set; }
    public string name { get; set; }
    public string nik { get; set; }
    public string Created { get; set; }
}

更新:在主线程中更新 UI

  Device.BeginInvokeOnMainThread(() => {
                EdtLocation.Text = result.AddressDetail;
                //...
            });

【讨论】:

  • 我已根据您建议的解决方案进行了尝试。谢天谢地,我设法得到了图片,但我不知道为什么调试在here 停止并且我无法获得其余的值?有什么想法吗?
  • @Machtal 你能用 Console.WriteLine(result.AddressDetail);检查什么是 result.AddressDetail,它是否为空? result.AddressDetail 的类型是什么?
  • result.AddressDetail 不为空且类型为字符串
  • @Machtal 那么它应该可以工作,就像 EdtLocation.Text = "abc";.
  • @Machtal 如果像 EdtLocation.Text = "abc"; 这样直接写会不会卡住?用那种方法?
猜你喜欢
  • 2015-03-03
  • 1970-01-01
  • 2017-10-25
  • 2014-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多