Hi I need to add items to list, it works when the list have elements but when list is empty javascript return undefined.
this is my function: namevalue is undefined when list is empty I think its main problem.
function submitAjaxForm(formId)
{
var form = $("<form></form>");
var targetID = formId.substr(1);
form.append($(formId).html());
var nameValue = $(formId).find('.showDictionariesList').first().find('input[type="hidden"]').first().attr('name');
var indexToCut = nameValue.indexOf('[', nameValue.indexOf('[', 0) + 1);
var featureIndex = nameValue.substring(0, indexToCut);
var contentVal = $("#dropDownList option:selected").val();
var returnValue = form.serializeArray();
returnValue[returnValue.length - 1].value = contentVal;
}
This list
public List<ShowDictionaryModel> ShowDictionaries { get; set; }
class of this items:
public class ShowDictionaryModel
{
public long Id { get; set; }
public string Value { get; set; }
public long? ProductId { get; set; }
public string FeatureId { get; set; }
internal static ShowDictionaryModel FromDto(DictionaryDto dto)
{
ShowDictionaryModel model = new ShowDictionaryModel();
model.Id = dto.Id;
model.Value = dto.Value;
model.ProductId = dto.ProductId;
model.FeatureId = dto.FeatureId;
return model;
}
}
Cshtml code: showDictionariesList is class who contains the list what i want to modify
#model MultiShop.Panel.Models.Product.AddProductFeatureTextModel
<div>
<div id="featureText-#Model.TypeId">
#Html.HiddenFor(m => m.TypeId)
#Html.HiddenFor(m => m.IsRequired)
#Html.HiddenFor(m => m.Name)
#Html.Label(Model.Name)
#Html.TextBoxFor(m => m.Value)
#if (Model.IsRequired)
{
<span class="requiredField"></span>
}
#Html.ValidationMessageFor(m => m.Value)
<div class="showDictionariesList">
#Html.EditorFor(m => m.ShowDictionaries)
</div>
#Html.DropDownListFor(m => m.SelectedDictionaryItemId, new SelectList(Model.DictionaryItems, "Id", "Value", Model.SelectedDictionaryItemId), new { id = "dropDownList" })
<input type="button" value="Save" onclick="#("submitAjaxForm('#featureText-" + #Model.TypeId + "')")" />
</div>
//}
your problem that youre trying to get attribute on non existing object
you should get it after check
var container = $(formId).find('.showDictionariesList').first();
var nameValueObj = container.find('input[type="hidden"]').first();
if (nameValueObj.length !== 0){
// input was found so we can get name attribute
var nameValue= nameValueObj.attr('name');
var indexToCut = nameValue.indexOf('[', nameValue.indexOf('[', 0) + 1);
// .........
} else{
// as far no input elements inside .showDictionariesList your logic to add first one item
// container.append(
}
I got answer for it. I just initialize list with basic element if is null. My experience with programming is very low so my code look bad but it works as I want.
if (!dictionaryType.HasItems())
{
DictionaryDto newForEmptyList = new DictionaryDto();
List<DictionaryDto> newList = new List<DictionaryDto>();
newForEmptyList.FeatureId = type;
newForEmptyList.ProductId = productId;
newForEmptyList.Value = "";
newForEmptyList.Id = -1;
newList.Add(newForEmptyList);
dictionaryType = newList.ToArray();
}
Related
I found out that my index page wasn't showing the updated user info for currently logged in user. So I changed the form page from:
<div class="col-xs-4">
<div class="col-md-4">
#Html.HiddenFor(model => model.SubmittedDate, new { Value = System.DateTime.Now })
#Html.HiddenFor(model => model.SubmittedBy, new { Value = Model.ADAccount })
</div>
</div>
**to:**
<div class="col-xs-4">
<div class="col-md-4">
#Html.HiddenFor(model => model.SubmittedDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.SubmittedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.HiddenFor(model => model.UpdatedDate, new { Value = System.DateTime.Now })
#Html.HiddenFor(model => model.UpdateBy, new { htmlAttributes = new { Value = Model.ADAccount } })
</div>
</div>
I had also tried changing the form page like this but it didn't change anything:
#Html.HiddenFor(model => model.UpdateBy, new { Value = Model.ADAccount })
The submit looks like this in the form page:
#(Html.Kendo().Button()
.Name("submit")
.Content("Submit")
.HtmlAttributes(new { #class = "k-primary" })
.Events(ev => ev.Click("onClick")))
But for some reason it's still not showing the UpdateBy in the Index list. I don't see a specific reference in the Controller for UpdateBy or SubmittedBy. I see them both in the ApplicantCapturedData.cs list:
public string UpdateBy { get; set; }
public string SubmittedBy { get; set; }
I see in ApplicantController.cs, the Edit Post puts some data in the DB, but doesn't mention the updateBy or SubmittedBy variables or model specifically. However, in the old code, the SubmittedBy variable change did show on the index list. I looked in the project, and there are no specific references to SubmittedBy besides ApplicantController
When I put a watch on UpdateBy, I see it go back and forth between the old user, me, and null. Apparently it ends with the old user, because that's what is displayed in the list of applicants on the index after the form is submitted.
Any thoughts on how to fix this? I'm new to MVC, and I'm not sure why this change isn't getting back to the model/db. When the applicantController gets the applicantCapturedData, it shows the old value for UpdateBy, not the new value.
The Edit Method should return current loged-in user to the view instead of BD data, but it's not. I'm not sure why.
I looked at controller not receiving model info, but it didn't seem like the same issue to me.
Let me know if you think I'm leaving any crucial info out that you need. I obviously can't post all of the mvc files and code here for clarity and sanity.
******Update*********
This is the Edit/Post method in ApplicantController.cs. It doesn't specifically refer to the SubmittedBy or UpdateBy, but the SubmittedBy part does show up in the index, even when we updated it in the form with current AD user:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ApplicantCapturedData applicantCapturedData)
{
var eRecordSchedulinglist = applicantCapturedData.ERecordScheduling;
var eRecordScheduling = new ERecordScheduling();
// int IDs = applicantCapturedData.ID;
//updating Provider License
var providerLicenselist = applicantCapturedData.ProviderLicense;
var providerLicense = new ProviderLicense();
var eprescribelist = applicantCapturedData.EPrescribe;
var eprescribe = new EPrescribe();
//updating payor table
var payorlist = applicantCapturedData.Payor;
var payor = new Payor();
//updating tax table
var taxlist = applicantCapturedData.TaxNPITaxonomy;
var tax = new TaxNPITaxonomy();
if (ModelState.IsValid)
{
//ERecordScheduling eRecordScheduling = new ERecordScheduling();
db.Entry(applicantCapturedData).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
int getid = applicantCapturedData.ID;
//Getting values for provider license already in db
var query = from p in db.ProviderLicenses
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in query)
{
db.ProviderLicenses.Remove(i);
}
db.SaveChanges();
int c = 1;
if (providerLicenselist != null)
{
var updatePLS = providerLicenselist.ToList();
// adding only new record to db
foreach (var i in updatePLS)
{
providerLicense.LicenseNumber = i.LicenseNumber;
providerLicense.State = i.State;
providerLicense.ProviderLicenseID = i.ProviderLicenseID;
i.ApplicantCapturedData_ID = getid;
if (providerLicense.ProviderLicenseID <= c)
{
providerLicense.ProviderLicenseID = providerLicense.ProviderLicenseID++;
}
db.ProviderLicenses.Add(i);
db.SaveChanges();
}
}
//getting Values already existing in db for Erecording Schedulign
var queryERS = from p in db.ERecordSchedulings
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in queryERS)
{
db.ERecordSchedulings.Remove(i);
}
db.SaveChanges();
if (eRecordSchedulinglist != null)
{
var updateESCH = eRecordSchedulinglist.ToList();
foreach (var item in updateESCH)
{
eRecordScheduling.DepartmentName = item.DepartmentName;
eRecordScheduling.Shedules = item.Shedules;
eRecordScheduling.VisitType = item.VisitType;
eRecordScheduling.GenericProvider = item.GenericProvider;
eRecordScheduling.ERecordSchedulingID = item.ERecordSchedulingID;
// a.ApplicantCapturedData_ID = newid;
item.ApplicantCapturedData_ID = getid;
if (eRecordScheduling.ERecordSchedulingID <= c)
{
eRecordScheduling.ERecordSchedulingID = eRecordScheduling.ERecordSchedulingID++;
}
//save to db
db.ERecordSchedulings.Add(item);
db.SaveChanges();
}
}
//Getting Values that already exisit in db for Taxonomy
var querytaxo = from p in db.TaxNPITaxonomies
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in querytaxo)
{
db.TaxNPITaxonomies.Remove(i);
}
db.SaveChanges();
if (taxlist != null)
{
var UpdateTaxo = taxlist.ToList();
foreach (var t in UpdateTaxo)
{
tax.GroupNPI = t.GroupNPI;
tax.Notes = t.Notes;
tax.TaxID = t.TaxID;
tax.TaxNPITaxonomyID = t.TaxNPITaxonomyID;
tax.Taxonomy = t.TaxID;
t.ApplicantCapturedData_ID = getid;
if (tax.TaxNPITaxonomyID <= c)
{
tax.TaxNPITaxonomyID = tax.TaxNPITaxonomyID++;
}
db.TaxNPITaxonomies.Add(t);
db.SaveChanges();
}
}
var queryeprescribe = from p in db.EPrescribes
where p.ApplicantCapturedData_ID == getid
select p;
foreach (var i in queryeprescribe)
{
db.EPrescribes.Remove(i);
}
db.SaveChanges();
if (eprescribelist != null)
{
var updateeprescribe = eprescribelist.ToList();
foreach (var t in updateeprescribe)
{
eprescribe.EPrescribeOptions = t.EPrescribeOptions;
eprescribe.ID = t.ID;
t.ApplicantCapturedData_ID = getid;
if (eprescribe.ApplicantCapturedData_ID <= c)
{
eprescribe.ApplicantCapturedData_ID = eprescribe.ApplicantCapturedData_ID++;
}
db.EPrescribes.Add(t);
db.SaveChanges();
}
}
//Geting values that already exist in db for Payors
var queryPayor = from p in db.Payors
where p.ApplicantCapturedData_ID == getid
select p;
//deleting the existing rows
foreach (var i in queryPayor)
{
db.Payors.Remove(i);
}
db.SaveChanges();
if (payorlist != null)
{
var updatepayor = payorlist.ToList();
foreach (var p in updatepayor)
{
payor.Pyor = p.Pyor;
payor.PayorID = p.PayorID;
p.ApplicantCapturedData_ID = getid;
if (payor.PayorID <= c)
{
payor.PayorID = payor.PayorID++;
}
db.Payors.Add(p);
db.SaveChanges();
}
}
return RedirectToAction("Index");
}
return View(applicantCapturedData);
}
Here's the save in ApplicantController.cs. It doesn't have a specific reference to UpdateBy or SubmittedBy either, and yet SubmittedBy used to update when I changed the AD user:
// [HttpPost]
public ActionResult Save(ApplicantCapturedData applicantCapturedData)
{
ViewBag.PostedBills = applicantCapturedData.BillingAreas;
applicantCapturedData.BillingAreas = applicantCapturedData.BillingAreas;
//updating eRecordScheduling
var list = applicantCapturedData.ERecordScheduling;
var a = new ERecordScheduling();
var OtherAddressList = applicantCapturedData.PracticeInfoOtherLocations;
var otheraddresses = new PracticeInfoOtherLocation();
//var payorlist = applicantCapturedData.Payor;
//var payor = new Payor();
// int IDs = applicantCapturedData.ID;
//updating Provider License
var providerLicenselist = applicantCapturedData.ProviderLicense;
var providerLicense = new ProviderLicense();
var Eprescribelist = applicantCapturedData.EPrescribe;
var eprescribe = new EPrescribe();
//updating payor table
var payorlist = applicantCapturedData.Payor;
var payor = new Payor();
//updating tax table
var taxlist = applicantCapturedData.TaxNPITaxonomy;
var tax = new TaxNPITaxonomy();
// var lastEnt = db.ERecordSchedulings.AsEnumerable().Where(i => i.ERecordSchedulingID.CompareTo(a.ERecordSchedulingID))
int c = 1;//lastEnter.LastOrDefault().ERecordSchedulingID;
if (ModelState.IsValid)
{
db.ApplicantCapturedDatas.Add(applicantCapturedData);
// db.ERecordSchedulings.Add(applicantCapturedData);
db.SaveChanges();
//db.ERecordSchedulings.Add(applicantCapturedData.ERecordScheduling);
//get the primary key id after adding to the Db
int newid = applicantCapturedData.ID;
if (applicantCapturedData.ERecordScheduling != null)
{
// check if we have more record on Erecord scheduling using the count
//if count is greater than zero we have record to add to db.
if (applicantCapturedData.ERecordScheduling.Count() > 0)
{
/*
* This loops thru the list and add record
*
*/
foreach (var item in list)
{
a.DepartmentName = item.DepartmentName;
a.Shedules = item.Shedules;
a.VisitType = item.VisitType;
a.GenericProvider = item.GenericProvider;
a.ERecordSchedulingID = item.ERecordSchedulingID;
// a.ApplicantCapturedData_ID = newid;
item.ApplicantCapturedData_ID = newid;
//if you put a breakpoint at the beginning of this class you will see that all id is 0 I had to increment the id so I don't override itself.
if (a.ERecordSchedulingID <= c)
{
a.ERecordSchedulingID = a.ERecordSchedulingID++;
}
//save to db
db.ERecordSchedulings.Add(item);
db.SaveChanges();
//item.LicenseNumber = a.LicenseNumber;
//item.State = a.State;
//item.ProviderLicenseID = a.ProviderLicenseID;
}
}
}
if (applicantCapturedData.ProviderLicense != null)
{
if (applicantCapturedData.ProviderLicense.Count() > 0)
{
foreach (var i in providerLicenselist)
{
providerLicense.LicenseNumber = i.LicenseNumber;
providerLicense.State = i.State;
providerLicense.ProviderLicenseID = i.ProviderLicenseID;
i.ApplicantCapturedData_ID = newid;
if (providerLicense.ProviderLicenseID <= c)
{
providerLicense.ProviderLicenseID = providerLicense.ProviderLicenseID++;
}
db.ProviderLicenses.Add(i);
db.SaveChanges();
}
}
}
if (applicantCapturedData.Payor != null)
{
if (applicantCapturedData.Payor.Count() > 0)
{
foreach (var p in payorlist)
{
payor.Pyor = p.Pyor;
payor.PayorID = p.PayorID;
p.ApplicantCapturedData_ID = newid;
if (payor.PayorID <= c)
{
payor.PayorID = payor.PayorID++;
}
db.Payors.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.PracticeInfoOtherLocations != null)
{
if (applicantCapturedData.PracticeInfoOtherLocations.Count() > 0)
{
foreach (var p in OtherAddressList)
{
otheraddresses.City = p.City;
otheraddresses.Fax = p.Fax;
otheraddresses.Phone = p.Phone;
otheraddresses.State = p.State;
otheraddresses.Street = p.Street;
otheraddresses.Suite = p.Suite;
otheraddresses.ZipCode = p.ZipCode;
otheraddresses.AppID = newid;
otheraddresses.ID = p.ID;
if (otheraddresses.ID <= c)
{
otheraddresses.ID = otheraddresses.ID++;
}
db.PracticeInfoOtherLocations.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.EPrescribe != null)
{
if (applicantCapturedData.EPrescribe.Count() > 0)
{
foreach (var p in Eprescribelist)
{
eprescribe.EPrescribeOptions = p.EPrescribeOptions;
eprescribe.ID = p.ID;
p.ApplicantCapturedData_ID = newid;
if (eprescribe.ID <= c)
{
eprescribe.ID = eprescribe.ID++;
}
db.EPrescribes.Add(p);
db.SaveChanges();
}
}
}
if (applicantCapturedData.TaxNPITaxonomy != null)
{
if (applicantCapturedData.TaxNPITaxonomy.Count() > 0)
{
foreach (var t in taxlist)
{
tax.GroupNPI = t.GroupNPI;
tax.Notes = t.Notes;
tax.TaxID = t.TaxID;
tax.TaxNPITaxonomyID = t.TaxNPITaxonomyID;
tax.Taxonomy = t.TaxID;
t.ApplicantCapturedData_ID = newid;
if (tax.TaxNPITaxonomyID <= c)
{
tax.TaxNPITaxonomyID = tax.TaxNPITaxonomyID++;
}
db.TaxNPITaxonomies.Add(t);
db.SaveChanges();
}
}
}
return RedirectToAction("Index");
}
return View(applicantCapturedData);
}
Im trying to send an array that contains some objects via connection made in SignalR, the connection is not a problem, everything works fine. When the data arrives to the view it is no longer the array i need to use.
This is the class:
public class Empresa
{
public string nombre { get; set; }
public int vidID { get; set; }
public string img64 { get; set; }
public string color { get; set; }
}
At the end the object will be something like this:
The object is send to the view and this is the output:
I have already tried with JsonConvert.SerializeObjectas i found on other threads, yet it doesnt seems to work. I tried to convert the data send with this jQuery.parseJSON(data) (Left) and with this JSON.parse(data)(Right); it throws an error on both cases as seen in the picture below.
I'm not sure if it is that way because the object sended is made this way:
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
var data = new List<Empresa>
{
new Empresa{nombre ="Globex Corp",color="red",vidId=1, img="data:image/jpeg;base64,blabla" },
new Empresa{nombre ="AM",color="blue",vidId=2, img="data:image/jpeg;base64,blabla" }
}
for(int i = 0; i<=6; i++)
{
_ar1.TryAdd(data[i].vidID, data[i]);
}
This is inside other function but it is the next one that involves the data send.
public IEnumerable<Empresa> GetArreglo()
{
return _ar1;
}
So far im not sure what could be wrong or if i need to aproach a different solution.
If any more info is needed ill post it. And even it is obvious im a newby still learning on this.
EDIT:
This is all the code involved:
// This is the JS
<script>
var ubi = '#ViewBag.ubicacion';
console.log("UbicaciĆ³n: " + ubi);
var conex = $.connection.channel;
var $marco = $('#marco');
var $imagen = $('#imagen');
var $empresa = $('#empresa');
function empezar() {
var min;
var max;
var pos;
var arreglo = new Array;
function init() {
conex.server.createGroup(ubi);
console.log("Entro al canal");
arreglo = conex.server.getArreglo(ubi);
//pos = arreglo.split('|');
//a.split is not a function
console.log(arreglo);
//console.log(pos);
setInterval(update, 6000);
}
function update() {
}
$.connection.hub.start().done(init);
}
window.onload = function() { empezar(); }
</script>
//It gets the conection to the HUB:
[HubName("channel")]
public class CanalHub : Hub
{
private readonly Canal _canal;
public CanalHub() : this(Canal.Instance) { }
public CanalHub(Canal canal)
{
_canal = canal;
}
public string[] GetArreglo(string ubi)
{
string[] array = _canal.GetArreglo(ubi);
return array;
//it is now a string[] because i wanted to
//try creating the obj with .split('|')
}
// And finally this is the last part involved:
public class Canal
{
private static Random random = new Random();
private volatile List<Canales> listaCan = new List<Canales>();
private readonly static Lazy<Canal> _instance = new Lazy<Canal>(() => new Canal(GlobalHost.ConnectionManager.GetHubContext<CanalHub>().Clients));
private readonly ConcurrentDictionary<int, Empresa> _datos = new ConcurrentDictionary<int, Empresa>();
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
private Canal(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
//Create the sample objects for the class
var datos = new List<Empresa>
{
new Empresa{nombre="Globex Corp", color="#A87F3D", vidID=1, img="balbal" },
new Empresa{nombre="AM", color="#535E89", vidID=2, img="balba" },
new Empresa{nombre="Frutijugos", color="#92191A", vidID=3, img="askldj" }
};
for (int i = 0; i <=6 ; i++)
{
_ar1.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 7; i <= 13; i++)
{
_ar2.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 14; i <= 20; i++)
{
_ar3.TryAdd(datos[i].vidID, datos[i]);
}
//sort them on 3 different arrays
}
private IHubConnectionContext<dynamic> Clients { get; set; }
public static Canal Instance
{
get { return _instance.Value; }
}
public string[] GetArreglo(string ubi)
{
string[] array = new string[7];
int i = 0;
if (ubi == "Campanario")
{
foreach (var item in _ar1)
{
array[i] += item.Value.nombre + "|";
array[i] += item.Value.color + "|";
array[i] += item.Value.img + "|";
array[i] += item.Value.vidID + "|";
i++;
}
return array;
}
//sort the array values and add them to the array
else return null;
}
It appears that your javascript promise is not set up correctly. The object in the view is the promise object and not the object returned. You are going to need to set up the promise correctly. deferred promise
Here My Classes
public class EmployeeProjectMaster
{
public int EmployeeProjectMasterId { get; set; }
//Class Variables
//Here i wants to get list of EmployeeProjectTransaction
//this is the way i tried
public EmployeeProjectMasterModelClient()
{
this.EmployeeProjectTransactionModel = new HashSet<EmployeeProjectTransactionModelClient>();
}
public virtual IEnumerable<EmployeeProjectTransactionModelClient> EmployeeProjectTransactionModel { get; set; }
}
public class EmployeeProjectTransaction
{
public int EmployeeProjecTransactiontId { get; set; }
public int EmployeeProjectMasterId { get; set; }
public int EmployeeId { get; set; }
public string EmployeeName {get;set;}
//Class Variables
}
public class Employee
{
public int EmployeeId { get; set; }
public string Employeefullname {get;set;}
}
Then here my linq query
//Get All Employee Project Details To Grid
public ActionResult GetAllEmployeeProjectDetails()
{
//DataTable Parameter
var draw = Request.Form.GetValues("draw").FirstOrDefault();
//Paging parameter
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//Paging parameter
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
//filter parameter
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
List<EmployeeProjectMasterModelClient> allEmployeeProject = new List<EmployeeProjectMasterModelClient>();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
//Database Query
using (InnoESolutionsDbEntities oInnoESolutionsDbEntities = new InnoESolutionsDbEntities())
{
var v = (from Epmm in oInnoESolutionsDbEntities.EmployeeProjectMasterModels
join Eptm in oInnoESolutionsDbEntities.EmployeeProjectTransactionModels
on Epmm.EmployeeProjectMasterId equals Eptm.EmployeeProjectMasterId
select new {Epmm, Eptm});
if (!string.IsNullOrEmpty(searchValue))
{
v = v.Where(b =>
b.Epmm.ProjectModel.ProjectName.Contains(searchValue)
);
}
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
//for make sort simpler we will add system.linq.dynamic reference
//v = v.OrderBy(sortColumn + " " + sortColumnDir);
v = v.OrderBy(a => a.Epmm.EmployeeProjectMasterId + " " + a.Eptm.EmployeeProjectMasterId);
}
recordsTotal = v.Count();
allEmployeeProject = v.Skip(skip).Take(pageSize).Where(y => y.Epmm.IsActive && !y.Epmm.IsDelete && y.Eptm.IsActive && !y.Eptm.IsDelete).Select(x => new EmployeeProjectMasterModelClient
{
EmployeeProjectMasterId = x.Epmm.EmployeeProjectMasterId,
ProjectId = x.Epmm.ProjectId,
ProjectName = x.Epmm.ProjectModel.ProjectName,
WorkDateS = SqlFunctions.DateName("day", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("month", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("year", x.Epmm.WorkDate),
SalaryForEachEmployee = x.Epmm.SalaryForEachEmployee,
EmployeeProjectTransactionModel = *************************************How to Load Trnsaction Details As A list Here
}).ToList();
}
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = allEmployeeProject });
}
Above c# function and Linq query for load angular data table. it's needs to select List Inside a List. i Wrote linq query for join. I don't know whether If it is correct or not.when you answer my question please consider that query. Have tried lot of time but i have failed. in query when i try to get record into allEmployeeProject . how to load transaction Details As a list inside allEmployeeProject list asterisk symbol indicates what i need to do. i wants list of employee for particular master record.
Here output what i want
MasterId | TransactionId |Employee Id | Employee Name
---------+---------------+------------+---------------
1 | 1 | 4 | name 1
| 2 | 2 | name 3
I think what you need is GroupBy method.
allEmployeeProject = v.Skip(skip).Take(pageSize).Where(y => y.Epmm.IsActive && !y.Epmm.IsDelete && y.Eptm.IsActive && !y.Eptm.IsDelete).Select(x => new EmployeeProjectMasterModelClient
{
EmployeeProjectMasterId = x.Epmm.EmployeeProjectMasterId,
ProjectId = x.Epmm.ProjectId,
ProjectName = x.Epmm.ProjectModel.ProjectName,
WorkDateS = SqlFunctions.DateName("day", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("month", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("year", x.Epmm.WorkDate),
SalaryForEachEmployee = x.Epmm.SalaryForEachEmployee
});
var allEmployeeProjectsByMaster = allEmployeeProject.GroupBy(x => x.EmployeeProjectMasterId).ToList();
Now you can have transaction list grouped by EmployeeProjectMaster with allEmployeeProjectsByMaster variable, just map it to relevant data model using Select.
MODEL - Employee.cs
public class Employee
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
public List<Employee> lstEmployees { get; set; }
}
CONTROLLER - EmpController.cs
public ActionResult Index()
{
Employee emp = new Employee();
emp.lstEmployees = new List<Employee>();
emp.lstEmployees.Add(new Employee() { id = 1, name = "ABCD", age = 15 });
emp.lstEmployees.Add(new Employee() { id = 2, name = "EFGH", age = 25 });
emp.lstEmployees.Add(new Employee() { id = 3, name = "IJKL", age = 35 });
ViewBag.EmpList = emp.lstEmployees;
return View();
}
VIEW - Index.cshtml
#Html.DropDownListFor(m => m.id, new SelectList(ViewBag.EmpList, "id", "name"), new { onchange = "SelectedIndexChanged(this)" })
<script type="text/javascript">
function SelectedIndexChanged(p) {
}
</script>
I want to display age at label
#Html.LabelFor(model => model.age)
on change of selection of drop down.
Try this..
<script type="text/javascript">
function SelectedIndexChanged(element) {
var optionSelected = $("option:selected", element);
var selectedAge = $(optionSelected).attr('data-age');
$('label[for="age"]').text(selectedAge);
}
</script>
It will add the label text with dropdown value..
Also you can try with this: $('label[for="age"]').html(selectedAge);
Edited:
<select name="id" id="id" onchange="SelectedIndexChanged(this)">
#if(ViewBag.EmpList != null)
{
foreach(var item in ViewBag.EmpList){
<option value="#item.id" data-age="#item.age">#item.name</option>
}
}
</select>
I have a slight problem here that each time I run the application the first radio button is always checked, I want to make nun of the radio buttons checked. How do I do this?
<div class="col-md-12">
<!--<i class="fa fa-child" aria-hidden="true"></i>-->
#Html.LabelFor(model => model.CCommmunication, "Choose your preferred way of communication", new { #style = "", #class = "", id = "" })
<span style="color: red;">*</span>
#*#Html.DropDownListFor(model => model.Profession, new SelectList(Model.Professions, "Id", "Name"), new { placeholder = "", #style = "", #class = "form-control", id = "Profession" })*#
#Html.EnumRadioButtonFor(model => model.CCommmunication, false,false,"communicationCB") <!--first 2 paramerters are false false communicationCB is the class-->
#Html.ValidationMessageFor(model => model.CCommmunication)
</div>
this is my Model
[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication CCommmunication
{ get; set; }
public enum Commmunication
{
[Display(Name = "Email", Order = 0)]
Email,
[Display(Name = "Mobile telephone", Order = 1)]
TelephoneNo,
[Display(Name = "Alternative telephone", Order = 2)]
TelephoneNoAlternative
}
This is my JavaScript
<script>
var checkedVal = $('.communicationCB input[name=CCommmunication]:checked').val(); //Added a variable to check the value
if (checkedVal == "TelephoneNo") { //if checked valuie
$('.confirmmobtelno').show(); //show this text box
} else {
$('.confirmmobtelno').hide(); //hide textbox
};
if (checkedVal == "TelephoneNoAlternative") { //if checked valuie == to TelephoneNoalternative
$('.confirmalttelno').show(); //show confirm alt tel no text box
} else {
$('.confirmalttelno').hide(); //else hide it
};
$('.communicationCB input[name=CCommmunication]').click(function () { //.communication class passed input name == model public communication
if ($(this).val() == "TelephoneNo") { //if value TelephoneNo selected in model
$('.confirmmobtelno').show(); //show this text box
} else {
$('.confirmmobtelno').hide(); //hide textbox
}
if ($(this).val() == "TelephoneNoAlternative") { //if value == to TelephoneNoalternative
$('.confirmalttelno').show(); //show confirm alt tel no text box
} else {
$('.confirmalttelno').hide(); //else hide it
}
});
Finally I have a enumRadioButton.cs
public static class HtmlHelper
{
public static MvcHtmlString EnumRadioButtonFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
bool includeNoneOption = true,
bool isDisabled = false,
string cssClass = null
) where TModel : class
{
var memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
throw new InvalidOperationException("Expression must be a member expression");
var name = ExpressionHelper.GetExpressionText(expression);
var fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
ModelState currentValueInModelState;
var couldGetValueFromModelState = htmlHelper.ViewData.ModelState.TryGetValue(fullName, out currentValueInModelState);
object selectedValue = null;
if (couldGetValueFromModelState && htmlHelper.ViewData.Model != null)
{
selectedValue = expression.Compile()(htmlHelper.ViewData.Model);
}
var enumNames = GetSelectItemsForEnum(typeof(TProperty), selectedValue).Where(n => !string.IsNullOrEmpty(n.Value)).ToList();
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
sb.AppendFormat(
"<ul class=\"radio-button-list{0}\">",
string.IsNullOrEmpty(cssClass) ? string.Empty : " " + cssClass);
foreach (var enumName in enumNames)
{
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
enumName.Value
);
if (id.StartsWith("-"))
id = id.Remove(0, 1);
var value = enumName.Value;
sb.AppendFormat(
//"<li>{2} <label for=\"{0}\">{1}</label></li>", //Originol puts data in a list
"{2} <label for=\"{0}\">{1}</label>",
id,
HttpUtility.HtmlEncode(enumName.Text),
isDisabled
? htmlHelper.RadioButtonFor(expression, value, new { id, disabled = "disabled" }).ToHtmlString()
: htmlHelper.RadioButtonFor(expression, value, new { id }).ToHtmlString()
);
}
sb.Append("</ul>");
return MvcHtmlString.Create(sb.ToString());
}
public static IList<SelectListItem> GetSelectItemsForEnum(Type enumType, object selectedValue)
{
var selectItems = new List<SelectListItem>();
if (enumType.IsGenericType &&
enumType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
enumType = enumType.GetGenericArguments()[0];
selectItems.Add(new SelectListItem { Value = string.Empty, Text = string.Empty });
}
var selectedValueName = selectedValue != null ? selectedValue.ToString() : null;
var enumEntryNames = Enum.GetNames(enumType);
var entries = enumEntryNames
.Select(n => new
{
Name = n,
DisplayAttribute = enumType
.GetField(n)
.GetCustomAttributes(typeof(DisplayAttribute), false)
.OfType<DisplayAttribute>()
.SingleOrDefault() ?? new DisplayAttribute()
})
.Select(e => new
{
Value = e.Name,
DisplayName = e.DisplayAttribute.Name ?? e.Name,
Order = e.DisplayAttribute.GetOrder() ?? 50
})
.OrderBy(e => e.Order)
.ThenBy(e => e.DisplayName)
.Select(e => new SelectListItem
{
Value = e.Value,
Text = e.DisplayName,
Selected = e.Value == selectedValueName
});
selectItems.AddRange(entries);
return selectItems;
}
}
}
To have none of the radio buttons selected, you make the property nullable
[Required(ErrorMessage = "Please select preferred way of communication option")]
public Commmunication? CCommmunication { get; set; }
If CCommmunication has an initial value of null, then no radio buttons will be selected.
But its unclear what you trying to do with all that (unnecessary) code in you extension method, in particular why you are creating IList<SelectListItem> (which is for generating a <select> tag). Your helper can simply be
public static class RadioButtonHelper
{
public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string name = ExpressionHelper.GetExpressionText(expression);
Type type = Nullable.GetUnderlyingType(metaData.ModelType);
if (type == null || !type.IsEnum)
{
throw new ArgumentException(string.Format("The property {0} is not an enum", name));
}
StringBuilder html = new StringBuilder();
foreach (Enum item in Enum.GetValues(type))
{
string id = string.Format("{0}_{1}", metaData.PropertyName, item);
StringBuilder innerHtml = new StringBuilder();
innerHtml.Append(helper.RadioButtonFor(expression, item, new { id = id }));
innerHtml.Append(helper.Label(id, item.ToDescription()));
TagBuilder div = new TagBuilder("div");
div.AddCssClass("radiobutton");
div.InnerHtml = innerHtml.ToString();
html.Append(div.ToString());
}
TagBuilder container = new TagBuilder("div");
container.AddCssClass("radiobutton-container");
container.InnerHtml = html.ToString();
return MvcHtmlString.Create(container.ToString());
}
}
which uses the following extension method
public static class EnumExtensions
{
public static string ToDescription(this Enum value)
{
if (value == null)
{
return null;
}
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
return value.ToString();
}
}
in association with the [Description] attribute applied to your enum values rather that the [Display] attribute (but you can easily modify that)