My view model as
public class StudViewModel
{
public StudLineViewModel()
{
StudLine = new List<CreateReqLineViewModel>();
}
public StudheaderViewModel StudHeader { get; set; }
public List<StudLineViewModel> StudLine { get; set; }
}
public class StudheaderViewModel
{
public int Roll_no { get; set; }
public DateTime? birthday_date { get; set; }
}
public class StudLineViewModel
{
public int Sub_Id { get; set; }
public double marks { get; set; }
}
var MainVMObj = new StudViewModel();
var StudHeaderObj = new StudheaderViewModel ();
StudHeaderObj.Roll_no =1;
StudHeaderObj.birthday_date =null;
MainVMObj.StudHeader = StudHeaderObj ;
MainVMObj.StudLine =null;
return Partialview("StudInfo",MainVMObj );
Code in View
#Html.TextBoxFor(model => model.StudHeader.birthday_date ,new { #class = "InputText", onclick = "javascript:NewCssCal (this.Id,'ddMMMyyyy','arrow','','','','future')" })
expected Result
1. birth day assign null but it show as default date like 01-Jan-0001.
I was debug i found issue at
MainVMObj.StudHeader = StudHeaderObj -->assign object value it make null value to default value. so birth date from null to default(01-01-001)
Please provide the solution
Editors Give the Ans not edit the Post
Related
I want to populate listview with information retrieved from database using WCF in C# and am not able to retrieve correct data for listview binding.
public interface IServicePl
{
[OperationContract]
[OperationContract]
IEnumerable<InterventiiCuEchipament> GetInterventiiCuEchipaments();
}
[DataContract]
public class InterventiiCuEchipament
{
[DataMember]
public string EchipamentInterventie { get; set; }
public int id_interventie { get; set; }
public string tip_interventie { get; set; }
public string responsabil { get; set; }
public DateTime data_finalizare { get; set; }
public bool status { get; set; }
}
public IEnumerable<InterventiiCuEchipament> GetInterventiiCuEchipaments()
{
try
{
IEnumerable<InterventiiCuEchipament> query = from sel1 in dataP.interventiis
join sel2 in dataP.sesizaris
on sel1.id_interventie equals sel2.id_sesizare
select new InterventiiCuEchipament()
{
id_interventie = sel1.id_interventie,
EchipamentInterventie = sel2.echipament,
tip_interventie = sel2.tip_sesizare,
responsabil = sel1.responsabil,
data_finalizare = (DateTime)sel1.data_finalizare,
status = (bool)sel1.status
};
return query;
}
On the client side I have the following code :
if (client.InnerChannel.State != CommunicationState.Faulted)
{
List<InterventiiCuEchipament> ListaInterventii = new List<InterventiiCuEchipament>();
ListaInterventii = client.GetInterventiiCuEchipamentsAsync().Result.ToList();
InterventiiList.ItemsSource = ListaInterventii;
InterventiiList.Items.Refresh();
}
Output from query is ok, like in this image
Output for listview binding is like in this image
Why I can see just the count of query? and not correct values returned by query.
If the query returns values, then ListaInterventii should also have values.
I wrote a similar demo, you can compare it.
You can use foreach to see if there is a value.
ListaInterventii = client.GetInterventiiCuEchipamentsAsync().Result.ToList();
foreach(var a in ListaInterventii)
{
int A = a.id_interventie;
}
Demo
public class ProductService : IServicePl
{
public IEnumerable<InterventiiCuEchipament> GetInterventiiCuEchipaments()
{
// This comes from database.
var _dbCountries = new List<InterventiiCuEchipament>
{
new InterventiiCuEchipament {id_interventie = 1, tip_interventie="1"},
new InterventiiCuEchipament {id_interventie = 2, tip_interventie="2"},
new InterventiiCuEchipament {id_interventie = 3, tip_interventie="3"},
};
return _dbCountries;
}
}
[ServiceContract]
public interface IServicePl
{
[OperationContract]
IEnumerable<InterventiiCuEchipament> GetInterventiiCuEchipaments();
}
[DataContract]
public class InterventiiCuEchipament
{
[DataMember]
[Key]
public int id_interventie { get; set; }
public string tip_interventie { get; set; }
}
client side
ServicePlClient client = new ServicePlClient();
List<InterventiiCuEchipament> ListaInterventii = new List<InterventiiCuEchipament>();
ListaInterventii = client.GetInterventiiCuEchipamentsAsync().Result.ToList();
im learning blazor and wanted to build some small dynamic form generator
i known that there is already something like VxFormGenerator but wanted to learn by myself a bit - at least for simple forms purposes.
so i have it like this:
DynamicFormsComponent:
<EditForm Model = "#Params" OnValidSubmit="OnValidSubmit">
<DataAnnotationsValidator/>
#if(Params != null ) #foreach (var field in Params.FormFields)
{
<div class="mb-3">
<label for= "#field.Id">#field.Label :</label>
#switch (field.Type)
{
case FormFieldType.Text:
{
<InputText id="#field.Id" #bind-Value="#field.StrValue" placeholder="#field.PlaceHolder" class="form-control"></InputText>
break;
}
case FormFieldType.Number:
{
<InputNumber id="#field.Id" #bind-Value="#field.IntValue" placeholder="#field.PlaceHolder" class="form-control"> ></InputNumber>
break;
}
case FormFieldType.Date:
{
<InputDate id="#field.Id" #bind-Value="#field.DateValue" placeholder="#field.PlaceHolder" class="form-control"></InputDate>
break;
}
default:
{
break;
}
}
</div>
}
<ValidationSummary></ValidationSummary>
<button type="submit" class="btn btn-primary">#Params?.SendButtonText</button>
public partial class DynamicFormComponent:ComponentBase
{
[Parameter]
public DynamicFormParams Params { get; set; } = new DynamicFormParams();
[Parameter]
public EventCallback<DynamicFormParams> OnValidSubmitCallback { get; set; }
void OnValidSubmit()
{
Console.WriteLine("onValidSubmit");
if (OnValidSubmitCallback.HasDelegate ) OnValidSubmitCallback.InvokeAsync(Params);
//NavigationManager.navigateto.....
}
}
public class DynamicFormParams
{
public List<DynamicFormField> FormFields { get; set; } = new List<DynamicFormField>();
public string FormTitle { get; set; } = string.Empty;
public string SendButtonText { get; set; } = "Send";
}
public class DynamicFormField
{
public string? Label { get; set; }
public string Id { get; set; } = Guid.NewGuid().ToString();
public string PlaceHolder { get; set; } = string.Empty;
public FormFieldType? Type { get; set; }
public string? StrValue { get; set; }
public int? IntValue { get; set; }
public DateTime? DateValue { get; set; }
}
public enum FormFieldType
{
Text,
Number,
Date
}
so the usage would be
<DynamicFormComponent Params="#p" OnValidSubmitCallback=#onChildFormSubmit ></DynamicFormComponent>
DynamicFormParams p = new DynamicFormParams()
{
FormTitle = "test form Title",
SendButtonText = "WyĆlij",
FormFields = new List<DynamicFormField>()
{
new DynamicFormField()
{
Label="testLabelStr",
Id="anyid-notGuId",
StrValue="a",
PlaceHolder="asdadsad",
Type=FormFieldType.Text
},
new DynamicFormField()
{
Label="testLabelInt",
Type=FormFieldType.Number,
PlaceHolder="enter nr"
},
new DynamicFormField()
{
Label="testLabelDate",
Type=FormFieldType.Date,
DateValue=DateTime.Parse("2021-04-01")
}
}
};
private void onChildFormSubmit(DynamicFormParams pp)
{
Console.WriteLine("from local variable");
Console.WriteLine(JsonSerializer.Serialize(p));
Console.WriteLine("from event arg");
Console.WriteLine(JsonSerializer.Serialize(pp));
}
and the question is:
how with this approach i can use form validation ?
i have no clasic'model' so probably would need something like add 'list of validators ' to my DynamicFormField class
and somehow force DataAnnotationsValidator to use this list ? is it possible withoud clasic 'model' and 'data annotations attributes' on it ?
thanks and regards
The only way to validate form without a model is to use the Blazorise validation system. https://blazorise.com/docs/components/validation.
PS. I'm a Blazorise creator.
I need to run validation on JSON input model by taking the value from one List and check if it exists in another. This value is a rating is from 1 - 5. If there is no matching number, then it should throw an error. Below is the code and this logic goes in the section commented with : //check if rating exist in score table
namespace Alpha.Model
{
// INPUT
public class AlphaCalcParamMethod
{
public ICollection<PortfolioInputModel> portfolios { get; set; }
public Setting settings { get; set; }
public bool Validation(ref string errString)
{
// Check if portfolio exists
if(portfolios == null || portfolios.Count < 1)
{
errString = "At least 1 Portfolio.";
return false;
}
//check if weight adds upto 1
foreach(var portfolio in portfolios)
{
// var holdings = new List<PortfolioHoldingInput>();
var weightAggregator = 0.00;
foreach(var holding in portfolio.portfolioHoldings)
{
weightAggregator += holding.fundWeight;
}
if (weightAggregator != 1)
{
errString = "Fund Weights should add upto 1";
}
return false;
}
//check if rating exist in score table
foreach(var portfolio in portfolios)
{
var holdings = new List<PortfolioHoldingInput>();
var scores = new List<Setting>();
foreach(var holding in holdings)
{
//fetch the value of fundRating double
foreach(var score in scores)
{
//check if the value above exist in grossAlpha's List fundRating
// if it doesn't return false
}
}
return false;
}
return true;
}
}
// OUTPUT
public class AlphaCalcResultMethod
{
public List<PortfolioOutputModel> portfolios { get; set; }
}
public class PortfolioInputModel
{
public string portfolioIdentifier { get; set; }
public ICollection<PortfolioHoldingInput> portfolioHoldings { get; set; }
}
public class PortfolioOutputModel
{
public string portfolioIdentifier { get; set; }
public double portfolioAlpha { get; set; }
public ICollection<PortfolioHoldingOutput> portfolioHoldings { get; set; }
}
public class PortfolioHoldingInput
{
public string fundIdentifier { get; set; }
public int fundRating { get; set; }
public double fundExpenseRatio { get; set; }
public double fundWeight { get; set; }
}
public class PortfolioHoldingOutput
{
public string fundIdentifier { get; set; }
public int fundRating { get; set; }
public double fundExpenseRatio { get; set; }
public double fundWeight { get; set; }
public double fundAlpha { get; set; }
}
public class Setting
{
public List<GrossAlpha> grossAlphas { get; set; }
}
public class GrossAlpha
{
public int fundRating { get; set; }
public double grossAlpha { get; set; }
}
}
If you are going to return additional values from method, you should use out parameters.
Don't specify type of variable in variable name. I.e. instead of errorString just use error. Hungarian notation and other tricks are not needed with modern IDEs.
Double type is not precise. You should avoid comparing it to integer values for equality. Prefer greater or less than comparisons.
Use LINQ to replace loops
Method name Validation is a noun. That is pretty confusing for method which is action and should a verb. Consider rename it to Validate or IsValid
Code
public bool IsValid(out string error)
{
if (portfolios?.Any() == false)
{
error = "At least 1 Portfolio.";
return false;
}
if (portfolios.Any(p => p.portfolioHoldings.Sum(h => h.fundWeight) < 1))
{
error = "Fund Weights should add upto 1";
return false;
}
var holdings = portfolios.SelectMany(p => p.portfolioHoldings);
var validRatings = new List<int> { 1, 2, 3, 4, 5 };
if (holdings.Any(h => !validRatings.Contains(h.fundRating)))
{
error = "Fund ratings should be in " + String.Join(",", validRatings);
return false;
}
error = "";
return true;
}
Note: if valid ratings are sequential numbers, then you can just check range of fundRating value:
if (holdings.Any(h => h.fundRating < 1 || 5 < h.fundRating))
Look this code:
if(!score.grossAlphas.Exists(x => x.fundRating == holding.fundRating))
{
return false;
}
it check if exists grossAlphas with fundRating equals holding.fundRating.
put it in the loop where you want to check, let me know if it is what you want and if it works.
I have a model structure as illustrate below.
public class GuideLineSectionsViewModel
{
public GuideLineSectionsViewModel()
{
SectionsSet = new List<SectionViewModel>();
}
public string Title { get; set; }
public List<SectionViewModel> SectionsSet { get; set; }
}
public class SectionViewModel
{
public SectionViewModel()
{
SectionsSet = new List<SectionViewModel>();
QuestionsSet = new List<QuestionViewModel>();
ProblemsSet = new List<ProblemViewModel>();
GoalsSet = new List<GoalViewModel>();
BarriersSet = new List<BarriersViewModel>();
QuestionReferencesSet = new List<QuestionReferenceViewModel>();
}
public string Heading { get; set; }
public List<SectionViewModel> SectionsSet { get; set; }
public List<QuestionViewModel> QuestionsSet { get; set; }
public List<ProblemViewModel> ProblemsSet { get; set; }
public List<GoalViewModel> GoalsSet { get; set; }
public List<BarriersViewModel> BarriersSet { get; set; }
public List<QuestionReferenceViewModel> QuestionReferencesSet { get; set; }
}
public class ProblemViewModel
{
public string Text { get; set; }
public bool Identified { get; set; }
public List<GoalViewModel> GoalsSet { get; set; }
public List<QuestionReferenceViewModel> QuestionReferencesSet { get; set; }
}
Now Based on the condition I need to update the every list value of the ProblemViewModel using linq.Below is the condition
public GuideLineSectionsViewModel FindGuidelineType(GuideLineSectionsViewModel guidelineSectionModel)
{
//GuideLineSectionsViewModel result = new GuideLineSectionsViewModel();
string title = guidelineSectionModel.Title;
int count = Regex.Matches(title, "Low Intensity").Count;
if (count > 0)
{
}
return guidelineSectionModel;
}
The guidelineSectionModel.Title will contain the text as "some value : Low Intensity". So i used the regx to filter the text. Is there other way i can directly check the condition in linq. and update the model model.
I want to update list value of ProblemViewModelmodel property value public bool Identified to "true"
Currently it contain only False value.
Please can anyone help me to solve the issue.
Have a look at following method. I could not put LINQ but I think this answer can solve your purpose. Again Some classes structure are missing in your question so you may need to put that in following method.
GuideLineSectionsViewModel FindGuidelineType(GuideLineSectionsViewModel guidelineSectionModel)
{
//GuideLineSectionsViewModel result = new GuideLineSectionsViewModel();
string title = guidelineSectionModel.Title;
int count = Regex.Matches(title, "Low Intensity").Count;
if (count > 0)
{
foreach(SectionViewModel svm in guidelineSectionModel.SectionsSet)
{
foreach(ProblemViewModel pvm in svm.ProblemsSet)
{
pvm.Identified = true;
}
}
}
return guidelineSectionModel;
}
If you prefer LINQ:
if(guideLine.Title.Contains("Low Intensity"))
{
guideLine.SectionsSet.ForEach(s => s.ProblemsSet.ForEach(ps => ps.Identified = true));
}
Note: please read this answer https://stackoverflow.com/a/2962689/1525637 due to possible performance problems with the Regex.Matches, you should use String.Contains instead.
I have a model class like this
namespace ConnectBLL.DTO.Response
{
public class CategorySettings
{
public bool NeedsLoginToViewLongText { get; set; }
public bool NeedsLoginToViewAnyDetails { get; set; }
public bool ShowAttachment { get; set; }
public string CategoryPageID { get; set; }
public string TpUrl { get; set; }
}
public class CategorySettingsListResponse
{
public List<CategorySettings> CategorySettingsList { get; set; }
}
}
And I am trying to add data to it like this
private readonly CategorySettings cs = new CategorySettings();
CategorySettingsListResponse csr=new CategorySettingsListResponse();
public string GetAllCategorySettings()
{
cs.NeedsLoginToViewLongText = true;
cs.NeedsLoginToViewAnyDetails = false;
cs.ShowAttachment = true;
cs.CategoryPageID = "1";
cs.TpUrl = "url";
csr.CategorySettingsList.Add(cs);
}
But this fails and gives an error
Object reference not set to an instance of an object.
Can any one point out what is I am doing wrong?
Somewhere, you need to initialize CategorySettingsList.
public class CategorySettingsListResponse
{
CategorySettingsListResponse() {
CategorySettingsList = new List<CategorySettings>();
}
public List<CategorySettings> CategorySettingsList { get; set; }
}
You are tying to use an instance of List before initializing. Before
csr.CategorySettingsList.Add(cs);
Insert:
if (csr.CategorySettingsList == null) {
csr.CategorySettingsList = new List<CategorySettings>();
}
You are using uncreated objects cs and CategorySettingsList, you should create them before use:
public string GetAllCategorySettings()
{
csr.CategorySettingsList = new ListCategorySettings<>();
var cs = new CategorySettings
{
NeedsLoginToViewLongText = true,
...
What is cs? Something missing?
You forgot to do this:
var cs = new CategorySettings();
Also
You need to instantiate the CategorySettingsList in constructor for CategorySettingsListResponse.