Xamarin binding sometimes invisible - list

Inside my Xamarin TicketPage.xaml the binding just shows after a change of the bindingname to notesBlobbed. So i need to change the binding name to notesBlobbed and change it back to notes for displaying the bindings. Moreover, the notes disappear when leaving the page and are not displayed at startup. The first picture shows what it looks like at startup and after leaving the page. The second picture shows how it looks like with the change. The question is how can i display the notes the whole time?
PS: notesBlobbed is needed to deserialize the list for the SQLite datebase.
How it looks like:
https://s20.directupload.net/images/220512/zjdu9nz2.jpg (cant display images because of my reputation)
How it should looks like:
https://s20.directupload.net/images/220512/p6ssqxjt.jpg
TicketPage.xaml
<ContentPage.Content>
<ScrollView>
<StackLayout Padding="10,5,10,5">
<ListView x:Name="ListViewTicket" HasUnevenRows="True" SelectionMode="None" SeparatorVisibility="None" Margin="0,0,0,0">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame CornerRadius="10" BorderColor="Black" Margin="0,5,0,5">
<StackLayout>
<Label>
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="ID: " FontAttributes="Bold" FontSize="18"/>
<Span Text="{Binding pkid}" FontSize="18"/>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<Label>
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="Ticketnummer: " FontAttributes="Bold" FontSize="18"/>
<Span Text="{Binding ticketNumber}" FontSize="18"/>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<Label>
<Label.FormattedText>
<FormattedString>
<FormattedString.Spans>
<Span Text="Status: " FontAttributes="Bold" FontSize="18"/>
<Span Text="{Binding status}" FontSize="18"/>
</FormattedString.Spans>
</FormattedString>
</Label.FormattedText>
</Label>
<BoxView HorizontalOptions="FillAndExpand" HeightRequest="3" Color="Gray"/>
<Label Text="Betreff" FontAttributes="Bold" FontSize="18"/>
<Label Text="{Binding subject}" FontSize="18" Margin="0,-5,0,0"/>
<Label TextType="Html" Text="{Binding description}" FontSize="12"/>
<Label Text="Notiz" FontAttributes="Bold" FontSize="18" Margin="0,-10,0,0"/>
<!-- here is the problem -->
<StackLayout BindableLayout.ItemsSource="{Binding notes}">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Label Text="{Binding .}" MaxLines="2" LineBreakMode="TailTruncation"/>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</StackLayout>
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ScrollView>
</ContentPage.Content>
TicketPage.cs
public partial class TicketPage : ContentPage
{
public TicketPage()
{
InitializeComponent();
OnAppearing();
}
//Update & Delete Zeiten
const int deleteInterval = 259200000; //3 Tage
const int updateInterval = 900000; //15 Mins
protected async override void OnAppearing()
{
//lädt Tickets
var ticketList = await App.Database.GetTicket();
//lässt Tickets anzeigen
ListViewTicket.ItemsSource = ticketList;
//alle Tickets durchgehen bezüglich Updates & Delete
foreach (var ticket in ticketList)
{
//überprüft wie lange Ticket geschlossen ist (löscht bei 3 Tagen)
if (ticket.status == "closed")
{
var currentTime = DateTime.Now;
TimeSpan duration = currentTime - ticket.closed;
var result = duration.TotalMilliseconds;
if (result > deleteInterval)
{
await App.Database.DeleteTicket(ticket);
}
}
else
{
//updatet Ticket nach 15 Minuten
var currentTime = DateTime.Now;
TimeSpan duration = currentTime - ticket.updated;
var result = duration.TotalMilliseconds;
if (result < updateInterval)
{
continue;
}
//GET an API um Status & Notizen abzurufen
IsBusy = true;
var ticketId = ticket.id;
var url = "https://.../api/ticket/info/" + ticketId;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("AuthenticationToken", "Token");
HttpResponseMessage response = await client.GetAsync(url);
//updatet Status und Notizen
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Ticket update = JsonConvert.DeserializeObject<Ticket>(content);
ticket.status = update.status;
ticket.updated = DateTime.Now;
if (ticket.status == "closed")
{
ticket.closed = DateTime.Now;
}
ticket.notes = update.notes;
IsBusy = false;
}
else
{
await DisplayAlert("Alert", "Die Verbindung ist fehlgeschlagen prüfen Sie Ihre Internetverbindung und kontaktieren Sie den Support.", "Ok");
}
}
}
}
}

Firstly,the OnAppearing() method should be used directly and don't call it in the constructor again.
Secondly,like Jason suggested, you should process the ticket first and then assign ItemsSource: ListViewTicket.ItemsSource = ticketList;.
Below is the pseudo code for your reference:
public partial class TicketPage : ContentPage
{
List<String> myList = new List<String>() { "05.05.2022 09:12: Test Kommentar 1", "05.05.2022 09:12: Test Kommentar 2" };
private ObservableCollection<Ticket> ticketList;
public TicketPage()
{
InitializeComponent();
//process ticket to generate data firstly
ticketList = new ObservableCollection<Ticket>
{
new Ticket(){pkid = "3", ticketNumber = "19748",status="open",subject="Title3",description = "Beschreibung",notes=myList },
new Ticket(){pkid = "4", ticketNumber = "19749",status="close",subject="Title4",description = "Beschreibung",notes=myList }
};
}
protected override void OnAppearing()
{
//lädt Tickets
//lässt Tickets anzeigen
ListViewTicket.ItemsSource = ticketList;
}
}

Related

Ionic 2 after used DomSanitizer change style didn't work

I tried to change style with DOM in my project, but in my browser didn't change anything. when i tried to create console the DOM structure was change. Any idea?
Here is my code:
HTML:
<div (press)="showBookmarkOption($event)">
<div *ngFor="let item of isicontent; let i = index" class="content-wrap datanum-{{i}}" #contentwrapper>
<h3 [innerHTML]="this.sanitizer.bypassSecurityTrustHtml(item.title)"></h3>
<div [innerHTML]="this.sanitizer.bypassSecurityTrustHtml(item.content)"></div>
</div>
</div>
TS:
showBookmarkOption(e){
this.BookmarkTargetDatanum = e.target.closest('.content-wrap').classList[1].replace('datanum-','');
let BookmarkTarget:any = e.target.closest('div').id;
if(BookmarkTarget == ''){
return false;
}
let BookmarkMarkdown:any = document.getElementById(BookmarkTarget);
let BookmarkMarkdownOffsetTop:any = BookmarkMarkdown.offsetTop;
let BookmarkMarkdownOffsetHeight:any = BookmarkMarkdown.offsetHeight;
this.bookmarkContent = e;
this.bookmarkContent.target.style.background = "yellow";
console.log(e.target);
actionSheet.present();
}
and the result is

Cannot do the set off process of prepayment with spesific bill using web services in Acumatica

I have a problem in set off processing of Prepayment document with spesific Bill document. It happen only for 1 vendor, because there are a lot of prepayment documents from this vendor (it's about more than 6000 records).
this below is my code.
sCon.getLoginSettlementVoucher(context);
AP301000Content billSchema2 = context.AP301000GetSchema();
List<Command> cmds = new List<Command>();
billSchema2.DocumentSummary.Type.Commit = false;
billSchema2.DocumentSummary.Type.LinkedCommand = null;
var command2 = new Command[]
{
new Value { Value = docTypeSV,
LinkedCommand = billSchema2.DocumentSummary.Type},
new Value { Value = refNbrSV,
LinkedCommand = billSchema2.DocumentSummary.ReferenceNbr},
billSchema2.Applications.DocTypeDisplayDocType,
billSchema2.Applications.ReferenceNbrDisplayRefNbr,
billSchema2.Applications.Balance,
billSchema2.Applications.AmountPaid
};
try
{
var applications = context.AP301000Export(command2, null, 0, false, true);
int rowApp = applications.Count(); int ind = 0;
foreach (var data in applications)
{
string docTypeApp = data[0].ToString();
string refNbrApp = data[1].ToString();
string balanceApp = data[2].ToString();
decimal balApp = Convert.ToDecimal(balanceApp);
string amountPaid = data[3].ToString();
string index = ind.ToString();
if (refNbrApp == AcuRefNbr)
{
billSchema2.DocumentSummary.Type.Commit = false;
billSchema2.DocumentSummary.Type.LinkedCommand = null;
billSchema2.Applications.ReferenceNbrDisplayRefNbr.LinkedCommand = null;
cmds.Add(new Value { LinkedCommand = billSchema2.DocumentSummary.Type, Value = "Bill" });
cmds.Add(new Value { LinkedCommand = billSchema2.DocumentSummary.ReferenceNbr, Value = refNbrSV });
cmds.Add(new Value { LinkedCommand = billSchema2.DocumentSummary.Vendor, Value = vVendCode });
cmds.Add(new Key
{
ObjectName = billSchema2.Applications.DocTypeDisplayDocType.ObjectName,
FieldName = billSchema2.Applications.DocTypeDisplayDocType.FieldName,
Value = docTypeApp
});
cmds.Add(new Key
{
ObjectName = billSchema2.Applications.ReferenceNbrDisplayRefNbr.ObjectName,
FieldName = billSchema2.Applications.ReferenceNbrDisplayRefNbr.FieldName,
Value = refNbrApp
});
cmds.Add(new Value { LinkedCommand = billSchema2.Applications.ServiceCommands.RowNumber, Value = index });
if (docAmtSV == balApp)
cmds.Add(new Value { LinkedCommand = billSchema2.Applications.AmountPaid, Value = docAmountSV });
else if (docAmtSV < balApp)
cmds.Add(new Value { LinkedCommand = billSchema2.Applications.AmountPaid, Value = docAmountSV });
else if (docAmtSV > balApp)
cmds.Add(new Value { LinkedCommand = billSchema2.Applications.AmountPaid, Value = balanceApp });
cmds.Add(billSchema2.Actions.Save);
var result2 = context.AP301000Submit(cmds.ToArray());
}
else
{
continue;
}
}
}
catch (Exception ex)
{
continue;
}
And then I got an exception message like this below in Submit process.
Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<!DOCTYPE html>
<html>
<head>
<title>Request timed out.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/AcuInterface' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Request timed out.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.Web.HttpException: Request timed out.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[HttpException (0x80004005): Request timed out.]
</pre></code>
</td>
</tr>
</table>
<br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1098.0
</font>
</body>
--.
Since the error you are getting is indicating a time out, and that you are only getting it for the one vendor that has around or more than 6000 prepayment documents, you might want to augment the time out value before making your call.
This question here deals with augmenting the time out value for a Screen Based API call : Link.
To resume what is being said there, please use the following line to set the timer to a bigger value.
context.Timeout = 700000;
I already fix this problem, I just have to increase timeout of HttpExecution in web.config file inside of Acumatica ERP instance folder.
..............
..............
by Default Acumatica will set this timeout = 300. It's mean 300 seconds or 5 minutes

Workflow XAML Custom Activity Parsing issue?

I've created a custom XAML Activity inherited from NativeActivity and IActivityTemplateFactory
The Designer shows the correct look and feel inside the Library I've defined.
However when I drop it on the Flow Surface of a workflow Console Application I don't see it rendered. The CPU pegs at 50% and if I run procmon.exe I see BUFFEROVERFLOW on the .XAML file and a NOT REPARSE error on the exe itself.
I do have the typeof Designer defined as the attribute of the class.
I've turned on Exceptions in the VS debug to see if an exception is being thrown but nothing ever comes out.
--CODE-- CS
[Designer(typeof(ITCRetryActivityDesigner))]
public sealed class ITCRetryActivity : NativeActivity, IActivityTemplateFactory
{
private static readonly TimeSpan DefaultRetryInterval = new TimeSpan(0, 0, 0, 1);
private readonly Variable<Int32> _attemptCount = new Variable<Int32>();
private readonly Variable<TimeSpan> _delayDuration = new Variable<TimeSpan>();
private readonly Delay _internalDelay;
public ITCRetryActivity()
{
_internalDelay = new Delay
{
Duration = new InArgument<TimeSpan>(_delayDuration)
};
Body = new ActivityAction();
MaxAttempts = 5;
ExceptionType = typeof(TimeoutException);
RetryInterval = DefaultRetryInterval;
}
[DebuggerNonUserCode]
public Activity Create(DependencyObject target)
{
return new ITCRetryActivity
{
Body =
{
Handler = new Sequence()
}
};
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
metadata.AddDelegate(Body);
metadata.AddImplementationChild(_internalDelay);
metadata.AddImplementationVariable(_attemptCount);
metadata.AddImplementationVariable(_delayDuration);
RuntimeArgument maxAttemptsArgument = new RuntimeArgument("MaxAttempts", typeof(Int32), ArgumentDirection.In, true);
RuntimeArgument retryIntervalArgument = new RuntimeArgument("RetryInterval", typeof(TimeSpan), ArgumentDirection.In, true);
metadata.Bind(MaxAttempts, maxAttemptsArgument);
metadata.Bind(RetryInterval, retryIntervalArgument);
Collection<RuntimeArgument> arguments = new Collection<RuntimeArgument>
{
maxAttemptsArgument,
retryIntervalArgument
};
metadata.SetArgumentsCollection(arguments);
ValidationError validationError;
if (Body == null)
{
validationError = new ValidationError("No Children are defined in this Retry Activity", true, "Body");
metadata.AddValidationError(validationError);
}
if (typeof (Exception).IsAssignableFrom(ExceptionType) != false) return;
validationError = new ValidationError("Exception type does not match", false, "ExceptionType");
metadata.AddValidationError(validationError);
}
protected override void Execute(NativeActivityContext context)
{
ExecuteAttempt(context);
}
private static Boolean ShouldRetryAction(Type exceptionType, Exception thrownException)
{
return exceptionType != null && exceptionType.IsInstanceOfType(thrownException);
}
private void ActionFailed(NativeActivityFaultContext faultcontext, Exception propagatedexception, ActivityInstance propagatedfrom)
{
Int32 currentAttemptCount = _attemptCount.Get(faultcontext);
currentAttemptCount++;
_attemptCount.Set(faultcontext, currentAttemptCount);
Int32 maxAttempts = MaxAttempts.Get(faultcontext);
if (currentAttemptCount >= maxAttempts)
{
// There are no further attempts to make
return;
}
if (ShouldRetryAction(ExceptionType, propagatedexception) == false)
{
return;
}
faultcontext.CancelChild(propagatedfrom);
faultcontext.HandleFault();
TimeSpan retryInterval = RetryInterval.Get(faultcontext);
if (retryInterval == TimeSpan.Zero)
{
ExecuteAttempt(faultcontext);
}
else
{
// We are going to wait before trying again
_delayDuration.Set(faultcontext, retryInterval);
faultcontext.ScheduleActivity(_internalDelay, DelayCompleted);
}
}
private void DelayCompleted(NativeActivityContext context, ActivityInstance completedinstance)
{
ExecuteAttempt(context);
}
private void ExecuteAttempt(NativeActivityContext context)
{
if (Body == null)
{
return;
}
context.ScheduleAction(Body, null, ActionFailed);
}
[Browsable(false)]
public ActivityAction Body
{
get;
set;
}
[DefaultValue(typeof(TimeoutException))]
public Type ExceptionType
{
get;
set;
}
public InArgument<Int32> MaxAttempts
{
get;
set;
}
public InArgument<TimeSpan> RetryInterval
{
get;
set;
}
}
}
--XAML--
<sap:ActivityDesigner x:Class="ITC.Common.Workflow.ITCRetryActivityDesigner"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation"
xmlns:conv="clr-namespace:System.Activities.Presentation.Converters;assembly=System.Activities.Presentation">
<sap:ActivityDesigner.Icon>
<DrawingBrush>
<DrawingBrush.Drawing>
<ImageDrawing>
<ImageDrawing.Rect>
<Rect Location="0,0"
Size="16,16">
</Rect>
</ImageDrawing.Rect>
<ImageDrawing.ImageSource>
<BitmapImage UriSource="d-metal-reload-arrows.jpg"></BitmapImage>
</ImageDrawing.ImageSource>
</ImageDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
</sap:ActivityDesigner.Icon>
<sap:ActivityDesigner.Resources>
<conv:ModelToObjectValueConverter x:Key="ModelItemConverter"
x:Uid="sadm:ModelToObjectValueConverter_1" />
<DataTemplate x:Key="Collapsed">
<TextBlock HorizontalAlignment="Center"
FontStyle="Italic"
Foreground="Gray">
Double-Click to View
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="Expanded">
<StackPanel Orientation="Vertical">
<Grid Name="contentGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Grid.Column="0"
HorizontalAlignment="Left"
VerticalAlignment="Center">
Exception Type:
</TextBlock>
<sapv:TypePresenter HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="6"
Grid.Row="0"
Grid.Column="1"
Filter="ExceptionTypeFilter"
AllowNull="false"
BrowseTypeDirectly="false"
Label="Exception Type"
Type="{Binding Path=ModelItem.ExceptionType, Mode=TwoWay, Converter={StaticResource ModelItemConverter}}"
Context="{Binding Context}" />
</Grid>
<sap:WorkflowItemPresenter Item="{Binding ModelItem.Body.Handler}"
HintText="Drop Activity"
Margin="6" />
</StackPanel>
</DataTemplate>
<Style x:Key="ExpandOrCollapsedStyle"
TargetType="{x:Type ContentPresenter}">
<Setter Property="ContentTemplate"
Value="{DynamicResource Collapsed}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=ShowExpanded}"
Value="true">
<Setter Property="ContentTemplate"
Value="{DynamicResource Expanded}" />
</DataTrigger>
</Style.Triggers>
</Style>
</sap:ActivityDesigner.Resources>
<Grid>
<ContentPresenter Style="{DynamicResource ExpandOrCollapsedStyle}"
Content="{Binding}" Height="16" VerticalAlignment="Top" />
</Grid>
How can I debug this situation?
Thanks.
I resolved my issue by removing the Exception type as stated in comments and not having the icon graphic (using the default since it's not all that important.

MVC 4 - sorting with LINQ doesn't work with Ajax.BeginForm and my For loop

I writing some code with C# and MVC and I have button for sorting a list of data by asc and desc. The logic works in my controller, I am able to call the method that sorts the list and in the breakpoint I can see that it has been sorted.
But it's weird because when I loop through my list in the partial view it never works. I use a breakpoint in my view to make sure it's the same order of items which it is. But it's like the new values don't render to the screen.
TeamManagement.cshtml
#model Website.Models.modelTeamSelect
#{
ViewBag.Title = "Football App";
}
#section featured {
}
#using (Ajax.BeginForm("_PartialTeams",
new
{
model = this.Model
},
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "divCreatedTeams",
InsertionMode = InsertionMode.Replace
}))
{
<div id="divTeams" style="float: left; padding: 10px;">
<h3>Create a new team:</h3>
#Html.LabelFor(m => m.team.TeamName)
#Html.TextBoxFor(m => m.team.TeamName)
<input type="submit" value="Add Team" name="btnSubmit" />
</div>
Html.RenderPartial("~/Views/Partials/_PartialTeams.cshtml");
}
_PartialTeams.cshtml
#model Website.Models.modelTeamSelect
<div id="divCreatedTeams" style="float: left; padding: 10px;">
<h3>Your created teams:</h3>
<input type="submit" value="Asc" name="btnSubmit" />
<input type="submit" value="Desc" name="btnSubmit" />
<br />
#if (Model.teams.Count > 0)
{
for (int i = 0; i < Model.teams.Count; i++)
{
#Html.EditorFor(m => m.teams[i].TeamName)
<input type="button" value="Update team name" name="btnSubmit"/>
<input type="button" value="Remove team" name="btnSubmit"/>
<br />
}
}
</div>
Sorting logic in my controller
[HttpPost]
public PartialViewResult _PartialTeams(string BtnSubmit, modelTeamSelect modelTeamSelect)
{
switch (BtnSubmit)
{
case "Add Team":
modelTeamSelect.teams.Add(modelTeamSelect.team);
break;
case "Asc":
FootballRepository = new Repository.FootballRepository();
modelTeamSelect.teams = FootballRepository.Sort(modelTeamSelect, BtnSubmit);
break;
case "Desc":
FootballRepository = new Repository.FootballRepository();
modelTeamSelect.teams = FootballRepository.Sort(modelTeamSelect, BtnSubmit);
break;
}
return PartialView("~/Views/Partials/_PartialTeams.cshtml", modelTeamSelect);
}
public List<Models.modelTeam> Sort(Models.modelTeamSelect modelTeamSelect, string sort)
{
switch (sort)
{
case "Asc":
modelTeamSelect.teams = modelTeamSelect.teams.OrderBy(t => t.TeamName).ToList();
break;
case "Desc":
modelTeamSelect.teams = modelTeamSelect.teams.OrderByDescending(t => t.TeamName).ToList();
break;
}
return modelTeamSelect.teams;
}
My main model with team collection
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Website.Models
{
public class modelTeamSelect
{
public modelTeamSelect()
{
teams = new List<modelTeam>();
team = new modelTeam();
}
public List<modelTeam> teams { get; set; }
public modelTeam team { get; set; }
}
}
My method Sort does it's job but in the view it never displays correctly. e.g. always wrong order.
Anyone have any ideas because I am stuck.
Screenshots
In the screenshots I click sort by Asc and you can see it says Newcastle as the first item in the list. But when the page renders it will say West Ham first even though it is iterating using the for loop.
All the Html helpers are preferring to use the ModelState values over the actual model values.
So even you have sorted in place your modelTeamSelect.teams in your action in the view #Html.EditorFor(m => m.teams[i].TeamName) call will use the original (before sorting) values form the ModelState.
The solution: if you are updating your action parameters in-place then just clear the ModelState before returning the View/PartialView:
[HttpPost]
public PartialViewResult _PartialTeams(string BtnSubmit,
modelTeamSelect modelTeamSelect)
{
// ... Do the sorting, etc.
ModelState.Clear();
return PartialView("~/Views/Partials/_PartialTeams.cshtml", modelTeamSelect);
}
You can read more about why the helpers are working like this in this article: ASP.NET MVC Postbacks and HtmlHelper Controls ignoring Model Changes

When I select a Country from the listbox1 then second listbox should display states from the selected country

I am Using MVVM Pattern.
when I select a Country from the listbox1 then second listbox
will display states from the selected country.
ListBox For Country
<pmControls:pmListBox x:Name="countryListBox" Grid.Row="1" Margin="3" ItemsSource="{Binding Countries}" SelectedItem="{Binding SelectedCountry,Mode=TwoWay}" >
<pmControls:pmListBox.ItemTemplate >
<DataTemplate >
<Button Command="{Binding DataContext.GetAllStatesCommand,ElementName=countryListBox}" Margin="3" Width="100" Height="25" Content="{Binding Title}" >
</Button>
</DataTemplate>
</pmControls:pmListBox.ItemTemplate>
</pmControls:pmListBox>
ListBox For State
<pmControls:pmListBox x:Name="stateListBox" Grid.Row="1" Margin="3" ItemsSource="{Binding States}">
<pmControls:pmListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding StateTitle}" ></TextBlock>
</DataTemplate>
</pmControls:pmListBox.ItemTemplate>
</pmControls:pmListBox>
In ModelView these are my commands:
command to get all Countries:
public void getCountries()
{
CountryServiceClient client = new CountryServiceClient();
client.GetCountryDetailsCompleted += (clientS, eventE) =>
{
if (eventE.Error == null)
{
foreach (var item in eventE.Result)
{
countries.Add(item);
}
}
};
client.GetCountryDetailsAsync();
}
command to get all states for selected Country:
public void ExecutegetAllStatesCommand(EventToCommandArgs args)
{
selectedState = new States();
states = new ObservableCollection<States>();
int cntry_id = this.SelectedCountry.Country_Id;
StateServiceClient client = new StateServiceClient();
client.GetStatesCompleted += (clientS, eventE) =>
{
if (eventE.Error == null)
{
foreach (var item in eventE.Result)
{
states.Add(item);
}
}
};
client.GetStatesAsync(cntry_id);
}
Here i got the data correctly in my list states but it doesnt appears on Xaml.
Please help.
You mentioned that the 'states' are being set correctly in the viewmodel, in that case the problem could be one of the following:
I noticed you are binding to 'States' (upper case S) and your code behind sets to 'states' (lower case S).
Have you implemented the INotifyPropertyChanged for the viewmodel and call the propertychanged event handler
Try handling the CollectionChanged of the ObservableCollection that you are adding States to as the propertychanged will not automatically trigger when adding items.