How to implement Expandable ListView in xamarin forms - mvvm

I'm using service to get some values from json.
I displaying them on home page (IrrigNetPage) where I have three tabs, so I want to sort them on diferents way on every tab.
Here's my model:
public class IrrigNetModel
{
public IrrigNetModelItem[] items { get; set; }
}
public class IrrigNetModelItem
{
public int ID { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
public string DateText { get; set; }
public int StationId { get; set; }
public string StationName { get; set; }
public float StationLongitude { get; set; }
public float StationLatitude { get; set; }
public int ServiceId { get; set; }
public string ServiceName { get; set; }
}
Here's a part of xaml code from View:
<StackLayout
Grid.Column="1"
Orientation="Horizontal"
HorizontalOptions="FillAndExpand"
BackgroundColor="{Binding LocationTabColor}"
Padding="10"
Margin="1">
<StackLayout.GestureRecognizers>
<TapGestureRecognizer Command="{Binding TabTappedCommand}" CommandParameter="location"/>
</StackLayout.GestureRecognizers>
<Image Source="{Binding LocationTabIcon}"
HorizontalOptions="Start"
VerticalOptions="Center"
WidthRequest="16"
HeightRequest="16"
Aspect="AspectFit"
x:Name="LocationIcon"/>
<Label Text="{i18n:Translate Location}"
VerticalOptions="FillAndExpand"
HorizontalOptions="FillAndExpand"
VerticalTextAlignment="Center"
HorizontalTextAlignment="Start"
TextColor="{Binding LocationTabTextColor}"/>
</StackLayout>
And, ofcourse here is part of ViewModel:
else if (tabName == "location")
{
ServiceTabColor = Color.FromHex("#f4f4f4");
LocationTabColor = Colors.MENU_SELECTED_ITEM;
MapTabColor = Color.FromHex("#f4f4f4");
ServiceTabIcon = "services.png";
LocationTabIcon = "location_sel.png";
MapTabIcon = "location.png";
ServiceTabTextColor = Colors.MENU_SELECTED_ITEM;
LocationTabTextColor = Color.FromHex("#ffffff");
MapTabTextColor = Colors.MENU_SELECTED_ITEM;
ListHederIcon = "location.png";
IsListVisible = IsListVisible;
IsGridHeaderVisible = true;
IsMapVisible = false;
if (ServiceName == "irrigNET")
{
FrameIcon = "service_irrig.png";
}
else
{
FrameIcon = "service_trap.png";
}
GroupServicesByLocation();
}
Where I set some proporties values and as you can see here I call method GroupServicesByLocation(); which looks like:
public void GroupServicesByLocation()
{
var groupedCollection = IrrigNetCollection.GroupBy(x => x.StationName);
}
public ObservableCollection<IrrigNetModelItem> IrrigNetCollection { get; set; } = new ObservableCollection<IrrigNetModelItem>();
public async void GetData()
{
base.OnAppearing();
dialog.Show();
var token = LocalData.Token;
var data = await IrrigNetService.GetServices(token, "sr");
var irrigNetModel = new IrrigNetModelItem();
foreach (var d in data.items)
{
IrrigNetCollection.Add(d);
if (d.ServiceName == "irrigNET")
{
IrrigCounter++;
FrameImage = "service_irrig_img.png";
FrameHeaderColor = Color.FromHex("#33A8F7");
ServiceName = "irrigNET";
FrameIcon = "service_irrig.png";
}
else
{
AlertCounter++;
FrameImage = "alert.png";
FrameHeaderColor = Color.FromHex("#2BB24B");
ServiceName = "alertNET";
FrameIcon = "service_trap.png";
}
}
dialog.Hide();
}

Related

How to insert payload data in many-to-many relationships with EF Core 5

I have this relationship between Licitadores and Ofertas
public class Licitador
{
public int Id { get; set; }
public string Nombre { get; set; }
[StringLength(maximumLength: 15)]
public string CodigoSAP { get; set; }
public List<Oferta> Ofertas { get; set; } = new List<Oferta>();
}
public class Oferta
{
[StringLength(maximumLength:6)]
public string Id { get; set; }
[StringLength(maximumLength: 5)]
public string IdPresentada { get; set; }
....
public List<Licitador> Licitadores { get; set; } = new List<Licitador>();
}
And the join table in the context
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<LicitacionesEnSolitario>().ToTable("LicitacionesSolitario");
modelBuilder.Entity<Licitador>()
.HasMany(o => o.Ofertas)
.WithMany(of => of.Licitadores)
.UsingEntity<LicitacionesEnSolitario>
(oo => oo.HasOne<Oferta>().WithMany(),
oo => oo.HasOne<Licitador>().WithMany())
.Property(oo => oo.Adjudicado)
.IsRequired();
}
I need this data in my entity/table LicitacionesEnSolitario in addition to PK y FK
public class LicitacionesEnSolitario
{
public int LicitadorId { get; set; }
public string OfertaId { get; set; }
public bool Adjudicado { get; set; }
public string Plazo { get; set; }
public decimal PresupuestoOfertado { get; set; }
public DateTime? FechaAdjudicacion { get; set; }
}
Here I insert the data importing them from another database
public int ImportarLicitacionesEnSolitario()
{
try
{
int registrosAñadidos = 0;
var registrosSAP = _contextSAP.LicitacionesEnSolitario
.FromSqlRaw("sql")
.ToList();
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
oferta.Licitadores.Add(licitador);
registrosAñadidos +=1;
}
_contextBoletus.SaveChanges();
return registrosAñadidos;
}
catch (Exception ex)
{
throw ex;
}
}
This works fine and insert data in "LicitacionesEnSolitario" but with this fields Adjudicado, Plazo, PresupuestoPfertado y FechaAdjudicacion with nulls.
I don't know how to insert them at the time I insert Licitadores and if I try to update after the Add method using the PKs I just added
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
oferta.Licitadores.Add(licitador);
var ls = _contextBoletus.Set<LicitacionesEnSolitario>()
.SingleOrDefault(ls => ls.OfertaId == oferta.Id & ls.LicitadorId == licitador.Id);
ls.Adjudicado = registroSAP.Adjudicado;
ls.PresupuestoOfertado = registroSAP.PresupuestoOfertado;
ls.FechaAdjudicacion = registroSAP.FechaAdjudicacion;
registrosAñadidos +=1;
}
_contextBoletus.SaveChanges();
return registrosAñadidos;
I get this error System.NullReferenceException: Object reference not set to an instance of an object.
Any idea, please?
Thanks
This is the best way I found
foreach (var registroSAP in registrosSAP)
{
var oferta = _contextBoletus.Ofertas.Find(registroSAP.OfertaId);
var licitador = _contextBoletus.Licitadores.Where(l => l.CodigoSAP == registroSAP.CodigoSAP).FirstOrDefault();
var ls = _contextBoletus.Set<LicitacionesEnSolitario>().Add(
new LicitacionesEnSolitario
{
LicitadorId = licitador.Id,
OfertaId = oferta.Id,
Adjudicado = registroSAP.Adjudicado,
Plazo = registroSAP.Plazo,
PresupuestoOfertado = registroSAP.PresupuestoOfertado,
FechaAdjudicacion = registroSAP.FechaAdjudicacion
});
registrosAñadidos += 1;
}
Thanks

Unable to access the navigation property of a newly created object

I am working on an asp.net core MVC framework + entity framework. where i got those model classes:-
public partial class Submission
{
public Submission()
{
SubmissionQuestionSubmission = new HashSet<SubmissionQuestionSubmission>();
}
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? Created { get; set; }
public virtual ICollection<SubmissionQuestionSubmission> SubmissionQuestionSubmission { get; set; }
}
public partial class SubmissionQuestion
{
public SubmissionQuestion()
{
SubmissionQuestionSubmission = new HashSet<SubmissionQuestionSubmission>();
}
public int Id { get; set; }
public string Question { get; set; }
public virtual ICollection<SubmissionQuestionSubmission> SubmissionQuestionSubmission { get; set; }
}
public partial class SubmissionQuestionSubmission
{
public int SubmissionQuestionId { get; set; }
public long SubmissionId { get; set; }
public bool? Answer { get; set; }
public virtual Submission Submission { get; set; }
public virtual SubmissionQuestion SubmissionQuestion { get; set; }
}
public class SubmissionCreate
{
public Submission Submission {set; get;}
public IList<SubmissionQuestion> SubmissionQuestion { set; get; }
public IList<SubmissionQuestionSubmission> SubmissionQuestionSubmission { set; get; }
}
and i have the following create view:-
#for (var i = 0; i < Model.SubmissionQuestion.Count(); i++)
{
<div class="form-group">
<input asp-for="#Model.SubmissionQuestion[i].Question" hidden />
<input asp-for="#Model.SubmissionQuestionSubmission[i].SubmissionQuestionId" hidden />
<label class="control-label" style="font-weight:bold">#Model.SubmissionQuestion[i].Question</label><br />
<input type="radio" asp-for="#Model.SubmissionQuestionSubmission[i].Answer" value="true" /><span style="color: #4d9b84;font-size:14px;font-weight:bold"> Yes</span><br />
<input type="radio" asp-for="#Model.SubmissionQuestionSubmission[i].Answer" value="false" /><span style="color: #4d9b84;font-size:14px;font-weight:bold"> No</span>
</div>
}
and the following create post method:-
public async Task<IActionResult> Create([Bind("Submission,SubmissionQuestionSubmission")] SubmissionCreate sc )
{
if (ModelState.IsValid)
{
var newsubmission = _context.Submission.Add(sc.Submission);
sc.Submission.Created = DateTime.Now;
await _context.SaveChangesAsync();
foreach (var v in sc.SubmissionQuestionSubmission)
{
v.SubmissionId = sc.Submission.Id;
_context.SubmissionQuestionSubmission.Add(v);
}
await _context.SaveChangesAsync();
but inside my action method if i try the following sc.Submission.SubmissionQuestionSubmission.FirstOrDefault(a => a.SubmissionQuestion.Question.StartsWith("Are you")).Answer i will get null reference exception where the sc.Submission.SubmissionQuestionSubmission.SubmissionQuestion will be null, although the relation of these objects are defined inside the database.. any advice?
FirstOrDefault could be null in any case. It doesn't related to this particular case. So, before using any property, it should be checked whether it is null or not.
var object = list.FirstOrDefault(x=>x.p1='aa');
if(object != null)
{
//use object.Answer
}

How to consume an external api rest?

I need to consume a Rest API from an ERP Site, where I will list some items from this site, but I do not find anything useful that can help me to consume
I am using json and http client to perform, but the error in the process recognize the site path
public partial class ProdutoPage : ContentPage
{
ListView lv = new ListView();
public ProdutoPage()
{
InitializeComponent();
iniciar();
}
private async void iniciar()
{
//tinyapp API = new tinyapp();
//var lista = API.ListaCategorias("automacao");
var client = new HttpClient();
client.DefaultRequestHeaders.Add("token", "");
client.BaseAddress = new Uri("https://api.tiny.com.br/api2/pedidos.pesquisa.php/");
var resp = await client.GetAsync("pedidos.pesquisa.php/");
if (resp.IsSuccessStatusCode)
{
var respStr = await resp.Content.ReadAsStringAsync();
var l = JsonConvert.DeserializeObject<List<Pedido>>(respStr);
lv.ItemsSource = l;
}
}
}
}
I need a list of ERP site requests
in ASP.Net has no error, but in xamarim it does not have the using System.Web.Script.Serialization to enable javascript
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Xml.Linq;
namespace mia.Webservices
{
public class TinyAPI
{
private const string URL_PEDIDOS = "https://api.tiny.com.br/api2/pedidos.pesquisa.php/";
private const string URL_OBTER_PEDIDO = "https://api.tiny.com.br/api2/pedido.obter.php/";
private string parametros = "?formato=json";
private string token_solucoes = "";
private string token_automacao = "";
/// <summary>
/// ListaPedidos é um método que lista todos os pedidos do Tiny de acordo com os parâmetros data inicial e data final.
/// </summary>
public List<Pedido> ListaPedidos(string empresa, string situacao, string data_inicial, string data_final)
{
int pagina = 1;
string token = "";
if (empresa.Equals("automacao"))
{
token = token_automacao;
}
else
{
if (empresa.Equals("solucoes"))
{
token = token_solucoes;
}
}
HttpClient client = new HttpClient();
var baseAddress = new Uri(URL_PEDIDOS);
client.BaseAddress = baseAddress;
List<Pedido> pedidos = new List<Pedido>();
HttpResponseMessage response = null;
if (data_inicial != null && data_inicial != "" && data_final != null && data_final != "")
{
response = client.GetAsync(parametros + "&token=" + token + "&dataInicial=" + data_inicial + "&dataFinal=" + data_final + "&situacao=" + situacao).Result;
}
else
{
response = client.GetAsync(parametros + "&pagina=" + pagina + "&token=" + token).Result;
}
string json = response.Content.ReadAsStringAsync().Result;
Dictionary<string, object> userObject = new JavaScriptSerializer().DeserializeObject(json) as Dictionary<string, object>;
if (userObject.ContainsKey("retorno"))
{
Object meta = userObject["retorno"];
Dictionary<string, object> dic_meta = (Dictionary<string, object>)meta;
if (dic_meta.ContainsKey("numero_paginas"))
{
int total_count = (int)dic_meta["numero_paginas"];
while (total_count >= pagina)
{
HttpResponseMessage response_2 = null;
if (data_inicial != null && data_inicial != "" && data_final != null && data_final != "")
{
response_2 = client.GetAsync(parametros + "&token=" + token + "&dataInicial=" + data_inicial + "&dataFinal=" + data_final + "&situacao=" + situacao).Result;
}
else
{
response_2 = client.GetAsync(parametros + "&pagina=" + pagina + "&token=" + token).Result;
}
string json_2 = response_2.Content.ReadAsStringAsync().Result;
Dictionary<string, object> userObject_2 = new JavaScriptSerializer().DeserializeObject(json_2) as Dictionary<string, object>;
Dictionary<string, object> objetos = (Dictionary<string, object>)userObject_2["retorno"];
if (objetos.ContainsKey("pedidos"))
{
Object[] pedidos_list = (Object[])objetos["pedidos"];
foreach (var item in pedidos_list)
{
Dictionary<string, object> pre_lista_pedidos = (Dictionary<string, object>)item;
Dictionary<string, object> list_pedidos = (Dictionary<string, object>)pre_lista_pedidos["pedido"];
Pedido pedido = new Pedido();
pedido.situacao = (string)list_pedidos["situacao"];
pedido.id = (string)list_pedidos["id"];
pedido.numero = (string)list_pedidos["numero"];
pedido.numero_ecommerce = (string)list_pedidos["numero_ecommerce"];
pedido.data_pedido = (string)list_pedidos["data_pedido"];
pedido.data_prevista = (string)list_pedidos["data_prevista"];
pedido.nome = (string)list_pedidos["nome"];
pedido.valor = (string)list_pedidos["valor"].ToString();
pedido.id_vendedor = (string)list_pedidos["id_vendedor"];
pedido.nome_vendedor = (string)list_pedidos["nome_vendedor"];
pedido.codigo_rastreamento = (string)list_pedidos["codigo_rastreamento"];
pedido.url_rastreamento = (string)list_pedidos["url_rastreamento"];
pedidos.Add(pedido);
}
}
total_count -= 1;
}
}
}
return pedidos;
}
}
This works:
var client = new HttpClient();
client.DefaultRequestHeaders.Add("token", "0dbffc6cbb412c01a90431f07631c0e00f2889d4");
client.BaseAddress = new Uri("https://api.tiny.com.br/api2/");
var resp = client.GetAsync("pedidos.pesquisa.php").GetAwaiter().GetResult();
After a research I discovered your API requires POST to return data:
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.tiny.com.br/api2/");
var parameters = new Dictionary<string, string> { { "token", "0dbffc6cbb412c01a90431f07631c0e00f2889d4" } };
var encodedContent = new FormUrlEncodedContent(parameters);
var resp = await client.PostAsync("pedidos.pesquisa.php", encodedContent);
var respStr = await resp.Content.ReadAsStringAsync();
> var client = new HttpClient();
client.BaseAddress = new Uri("https://api.tiny.com.br/api2/");
var resp = client.GetAsync("pedidos.pesquisa.php?token=********&formato=json").Result;
if (resp.IsSuccessStatusCode)
{
var respStr = resp.Content.ReadAsStringAsync().Result;
var l = JsonConvert.DeserializeObject<List<Pedido>>(respStr);
lv.ItemsSource = l;
}`
doing so he located the token, but an error in Json, follows an example of json from the Pedido list
{
"retorno": {
"status_processamento": 3,
"status": "OK",
"pagina": "1",
"numero_paginas": "1",
"pedidos": [
{
"pedido": {
"id": 123456,
"numero": 123456,
"numero_ecommerce": "12",
"data_pedido": "01/01/2013",
"data_prevista": "10/01/2013",
"nome": "Cliente Teste",
"valor": "100.25",
"id_vendedor": "123456",
"nome_vendedor": "Vendedor Teste",
"situacao": "Atendido"
}
},
{
"pedido": {
"id": 123456,
"numero": 123458,
"numero_ecommerce": "15",
"data_pedido": "01/01/2013",
"data_prevista": "10/01/2013",
"nome": "Cliente Teste 3",
"valor": "50.25",
"id_vendedor": "",
"nome_vendedor": "",
"situacao": "Aberto"
}
}
]
}
}
error Newtonsoft.Json.JsonSerializationException:
pedido class
public class Pedido
{
public string id { get; set; }
public string numero { get; set; }
public string numero_ecommerce { get; set; }
public string data_pedido { get; set; }
public string data_prevista { get; set; }
public string nome { get; set; }
public string valor { get; set; }
public string id_vendedor { get; set; }
public string nome_vendedor { get; set; }
public string situacao { get; set; }
public string codigo_rastreamento { get; set; }
public string url_rastreamento { get; set; }
public string data_faturamento { get; set; }
public Cliente cliente { get; set; }
public List<Produto_Servico> produtos_servicos { get; set; }
}
Class Pedidos
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace MacVendas.Models.API
{
public class Pedido
{
public class Pedido2
{
public string id { get; set; }
public string numero { get; set; }
public string numero_ecommerce { get; set; }
public string data_pedido { get; set; }
public string data_prevista { get; set; }
public string nome { get; set; }
public string valor { get; set; }
public string id_vendedor { get; set; }
public string nome_vendedor { get; set; }
public string situacao { get; set; }
public string codigo_rastreamento { get; set; }
public string url_rastreamento { get; set; }
}
public class Pedido1
{
public string pedido { get; set; }
}
public class Retorno
{
public string status_processamento { get; set; }
public string status { get; set; }
public string pagina { get; set; }
public string numero_paginas { get; set; }
public List<Pedido1> pedidos { get; set; }
}
public class RootObject
{
public Retorno retorno { get; set; }
}
}
}
I was able to read the list of categories that is smaller
using System;
using System.Collections.Generic;
using System.Text;
namespace MacVendas.Models.API
{
public class Categoria
{
public class Retorno
{
public string id { get; set; }
public string descricao { get; set; }
public List<object> nodes { get; set; }
}
public class RootObject
{
public List<Retorno> retorno { get; set; }
}
}
}
Produtopagexaml.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using MacVendas.Classes;
//using macvendas.services;
using MacVendas.Models.API;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MacVendas.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ProdutoPage : ContentPage
{
public ProdutoPage()
{
InitializeComponent();
Iniciar();
}
private void Iniciar()
{
var client = new HttpClient();
var resp = client.GetAsync("https://api.tiny.com.br/api2/produtos.categorias.arvore.php?token=*****&formato=json").Result;
string respStr = resp.Content.ReadAsStringAsync().Result;
Categoria.RootObject ObjPedidotList = new Categoria.RootObject ();
if (respStr != "")
{
ObjPedidotList = JsonConvert.DeserializeObject<Categoria.RootObject>(respStr);
}
//Binding listview with server response
listviewConacts.ItemsSource = ObjPedidotList.retorno;
}
}
}
produto.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="MacVendas.Pages.ProdutoPage">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Margin="10" Text="JSON Parsing" FontSize="25" />
<ListView x:Name="listviewConacts" Grid.Row="1" HorizontalOptions="FillAndExpand" HasUnevenRows="True" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid HorizontalOptions="FillAndExpand" Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Text="{Binding descricao}" HorizontalOptions="StartAndExpand" Grid.Row="0" TextColor="Blue" FontAttributes="Bold"/>
<!--<Label Text="{Binding numero}" HorizontalOptions="StartAndExpand" Grid.Row="1" TextColor="Orange" FontAttributes="Bold"/>
<Label Text="{Binding valor}" HorizontalOptions="StartAndExpand" Grid.Row="2" TextColor="Gray" FontAttributes="Bold"/>-->
<BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" Grid.Row="3" HorizontalOptions="FillAndExpand" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage>

selectList razor tag helpers asp.netCore

I want to make a drop down list of "Trailers" and "Customers" available in my "Order" form. I am able to use the Html tag helper to pass Trailer data from database to the view in the "Order" form but i am not able to do the same for Customers using the razor select tag helper. Why isn't the razor select tag helper not passing values from the database to the view? Below are snippets of my code. I am confused as to why it's not working
Trailer Class
public class Trailer
{
public string SerialNumber { get; set; }
public string TrailerNumber { get; set; }
public string TrailerStatus { get; set; }
public int TrailerID { get; set; }
public virtual Order OrderforTrailer { get; set; }
public Trailer()
{
TrailerStatus = "Available";
}
}
Customer class
public class Customer
{
public string CustomerName { get; set; }
public string StreetNumber { get; set; }
public string StreetName { get; set; }
public string ZipCode { get; set; }
public string State { get; set; }
public int CustomerID { get; set; }
public IList<Order> CustomerOrders { get; set; }
}
Order Class
public class Order
{
public string OrderNumber { get; set; }
public string OrderStatus { get; set; }
public int OrderID { get; set; }
public int TrailerForLoadID { get; set; }
public virtual Trailer TrailerForLoad { get; set; }
public int CustomerOrdersID { get; set;}
public virtual Customer CustomerOrders { get; set; }
public Order()
{
OrderStatus = "Available";
}
}
AddOrderViewModel
public string OrderNumber { get; set; }
public int TrailerID { get; set; }
public List<SelectListItem> TrailersForLoad { get; set; }
public int CustomerID { get; set; }
public List<SelectListItem> CustomersOrder { get; set; }
public AddOrderViewModel()
{
}
public AddOrderViewModel(IEnumerable<Trailer> trailersForLoad, IEnumerable<Customer> customersOrder)
{
TrailersForLoad = new List<SelectListItem>();
foreach (var trailer in trailersForLoad)
{
TrailersForLoad.Add(new SelectListItem
{
Value = (trailer.TrailerID).ToString(),
Text = trailer.TrailerNumber
});
};
CustomersOrder = new List<SelectListItem>();
foreach (var customer in customersOrder)
{
CustomersOrder.Add(new SelectListItem
{
Value = (customer.CustomerID).ToString(),
Text = customer.CustomerName
});
};
}
}
Order controller
public IActionResult Add()
{
IList<Trailer> trailerForLoad = context.Trailers.Where
(c => c.TrailerStatus == "Available").ToList();
IList<Customer> customerOrder = context.Customers.ToList();
AddOrderViewModel addOrderViewModel =
new AddOrderViewModel(trailerForLoad, customerOrder);
return View(addOrderViewModel);
}
[HttpPost]
public IActionResult Add(AddOrderViewModel addOrderViewModel)
{
if (ModelState.IsValid)
{
Order newOrder = new Order()
{
OrderNumber = addOrderViewModel.OrderNumber,
TrailerForLoad = context.Trailers.
Where(x => x.TrailerID == addOrderViewModel
.TrailerID).Single(),
CustomerOrders = context.Customers
.Single(x => x.CustomerID==addOrderViewModel.CustomerID)
};
context.Orders.Add(newOrder);
trailerSelected = context.Trailers.Where(x =>
x.TrailerID == addOrderViewModel.TrailerID).Single();
trailerSelected.TrailerStatus = "Unavailable";
context.SaveChanges();
return Redirect("/Order");
}
return View(addOrderViewModel);
}
The form in the view should display a list of customers
<form asp-controller="Order" asp-action="Add" method="post">
<fieldset>
<div class="form-group">
<label asp-for="OrderNumber">Order number </label>
<input class="form-control" asp-for="OrderNumber" />
<span asp-validation-for="OrderNumber"></span>
</div>
<div class="form-group">
<label asp-for="TrailersForLoad">Trailer</label>
#Html.DropDownListFor(x => x.TrailerID, Model.TrailersForLoad)
<span asp-validation-for="TrailersForLoad"></span>
</div>
<div class="form-group">
<label asp-for="CustomerID">Customers Name</label>
<select asp-for="CustomerID"
asp-items="Model.CustomersOrder"></select>
<span asp-validation-for="CustomerID"></span>
</div>
<div>
<input type="submit" value="Submit" name="submitButton" />
</div>
</fieldset>
You are using the SELECT tag helper incorrectly. In your current code, you are using a self closing tag approach! Instead you should use an explicit </SELECT> closing tag
This should work
<select asp-for="CustomerID" asp-items="Model.CustomersOrder"></select>

Why model in Entity Framework 6 can not serialize the data?

I try to get data from model and pass to client with json format. I wrote this code but when execute the code, I get an internal server error. When debugging code, data is shown such as this image.
Please advice.
[HttpPost]
public ActionResult GetCity(int idCountry)
{
TravelEnterAdminTemplate.Models.LG.MyJsonResult myresult = new Models.LG.MyJsonResult();
try
{
List<City> citylist = new List<City>();
var citystable = db.Cities.Where(p => p.CountryId == idCountry).ToList();
if (citystable != null)
{
foreach (var city in citystable)
{
myresult.obj = citystable;
}
myresult.Result = true;
}
else
{
myresult.Result = false;
myresult.message = "داده ای یافت نشد";
}
}
catch (Exception e)
{
errorlog.Error("DeleteShopping", "157", e.Source.ToString(), e.Message);
myresult.Result = false;
myresult.message = "خطا در بارگذاری اطلاعات";
}
return Json(myresult, JsonRequestBehavior.AllowGet);
}
City Entity :
namespace TravelEnterAdminTemplate.Models.dbModel
{
using System;
using System.Collections.Generic;
public partial class City
{
public City()
{
this.ArtPlaces = new HashSet<ArtPlace>();
this.Historicals = new HashSet<Historical>();
this.Hospitals = new HashSet<Hospital>();
this.Hotels = new HashSet<Hotel>();
this.PhotoTables = new HashSet<PhotoTable>();
this.PhotoTables1 = new HashSet<PhotoTable>();
this.Restaurants = new HashSet<Restaurant>();
this.Shoppings = new HashSet<Shopping>();
}
public int Id { get; set; }
public string NameFA { get; set; }
public string NameEN { get; set; }
public int CountryId { get; set; }
public virtual ICollection<ArtPlace> ArtPlaces { get; set; }
public virtual Country Country { get; set; }
public virtual ICollection<Historical> Historicals { get; set; }
public virtual ICollection<Hospital> Hospitals { get; set; }
public virtual ICollection<Hotel> Hotels { get; set; }
public virtual ICollection<PhotoTable> PhotoTables { get; set; }
public virtual ICollection<PhotoTable> PhotoTables1 { get; set; }
public virtual ICollection<Restaurant> Restaurants { get; set; }
public virtual ICollection<Shopping> Shoppings { get; set; }
}
}