How to pass 2 lists to 1 view - list

I want to show recent and incoming appointments in my view(one page).Here is my controller where can i add the second list and how can i pass it to same view?I know I cant return two list but there must be way for it?
public ActionResult Index()
{
if (Session["UserEmail"] != null)
{
string Email = (string)Session["UserEmail"];
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
ViewBag.FirstName = patient.Name;
ViewBag.LastName = patient.Surname;
ViewBag.BirthDate = patient.Birthday;
ViewBag.Email = patient.Email;
}
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
var listrecent = (from y in db.Appointments
where y.PatientNo == patient.PatientNo
where y.Date < DateTime.Today
orderby y.Date descending
select y).Take(5);
var TempRecent = new List<Models.AppModel>();
foreach (var item in listrecent)
{
var Temp = new Models.AppModel();
Temp.AppNo = item.AppNo;
Temp.PatientNo = (Int32)item.PatientNo;
Temp.Date = (DateTime)item.Date;
Temp.Status = item.Status;
Temp.Description = item.Description;
TempRecent.Add(Temp);
}
return View(TempRecent);
}
}
else
{
return RedirectToAction("RegAndLogin", "User");
}
}
}
}
and here is my view part
#model IEnumerable<DentAppSys.Models.AppModel>
#using System.Web.Helpers
#{
ViewBag.Title = "Index";
}
<section class="Patient-Dashboard">
<div id="dashboard_left">
<h1> Recent Appointments</h1>
#{
var Mygrid = new WebGrid(Model, selectionFieldName: "SelectedRow");
}
#Mygrid.GetHtml(
displayHeader: true,
mode: WebGridPagerModes.FirstLast,
columns: Mygrid.Columns
(
Mygrid.Column("Appointment No", "Appointment No",format: #<text>#item.AppNo</text>),
Mygrid.Column("Patient No", "Patient No", format: #<text>#item.PatientNo</text>) ,
Mygrid.Column("Description", "Description", format: #<text>#item.Description</text>),
Mygrid.Column("Date", "Date", format: #<text>#item.Date.ToString("yyyy/MM/dd")</text>),
Mygrid.Column("Status", "Status", format: #<text>#item.Status</text>)
))
</div>
<div id="dashboard_right">
<br/>
<h1>Incoming Appointments</h1>
/* HERE I WANT TO ADD MY SECOND LIST*/
</div>
</section>
Edit:
and after using two instances of the AppModel I get error when I try to equal Temp.RecentIncoming.AppNo=item.AppNo.
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
var listincoming = (from y in db.Appointments
where y.PatientNo == patient.PatientNo
where y.Date > DateTime.Today
orderby y.Date descending
select y).Take(5);
var TempIncoming = new List<Models.RecentIncoming>();
foreach (var item in listincoming)
{
var Temp = new Models.RecentIncoming.;
Temp.RecentIncoming.AppNo?????= item.AppNo;
Temp.PatientNo = (Int32)item.PatientNo;
Temp.Date = (DateTime)item.Date;
Temp.Status = item.Status;
Temp.Description = item.Description;
TempIncoming.Add(Temp);
}
return View(TempIncoming);
}

Instead of having IEnumerable as your model, create a new model class that has two instances of the AppModel as well as any other additional data you need to pass to the view...
public class MyAppointments
{
public IEnumerable<DentAppSys.Models.AppModel> RecentAppts;
public IEnumerable<DentAppSys.Models.AppModel> IncomingAppts;
public MyAppointments() { }
}
...
return View( new MyAppointments() { RecentAppts=TempRecent, IncomingAppts=TempIncoming } );
Change the view to...
#model MyAppointments
...
#{
var MyRecentgrid = new WebGrid(Model.RecentAppts, selectionFieldName: "SelectedRow");
var MyIncomingGrid = new WebGrid(Model.IncomingAppts, selectionFieldName: "SelectedRow");
}

Related

Test Automapper return collection or not

I am testing one of my services - movieService. GetLatestMovies method should return all movies, ordered by date. I am using automapper to map the entity Movie to MovieViewModel.
* Question 1: * How am I supposed to test that, should I set the return collection in the test or what?
* Question 2: * I am filling the InMemory database with a few movies and I am expecting correct ordered result from the movieService, how am I supposed to check, If the service is returning correct result, If I set the return from the automapper?
TestUtils.FillContextWithActorsMoviesAndGenres(options) - just fills the context with a few movies.
This is the movieService method I am testing
public async Task<ICollection<MovieViewModel>> GetLatestMoviesAsync()
{
var movies = await this.context.Movies
.Include(um => um.ApplicationUserMovie)
.ThenInclude(u => u.User)
.Include(x => x.Genre)
.Include(x => x.MovieActor)
.ThenInclude(x => x.Actor)
.OrderByDescending(x => x.CreatedOn).ToListAsync();
var returnMovies = this.mappingProvider.MapTo<ICollection<MovieViewModel>>(movies);
return returnMovies;
}
[TestMethod]
public async Task Return_TwoMoviesWithHighestRating()
{
var dabataseName = nameof(Return_TwoMoviesWithHighestRating);
var options = TestUtils.GetOptions(dabataseName);
// We fill the context with data and save it.
TestUtils.FillContextWithActorsMoviesAndGenres(options);
var movieOne = new MovieViewModel()
{
Name = "BestRatedMovieTest",
Duration = 90,
Director = "TestDirector",
Storyline = "TestStoryline",
ImageUrl = "TestImageUrl",
Genre = "Comedy"
};
var movieTwo = new MovieViewModel()
{
Name = "SecondMovieTestName",
Duration = 90,
Director = "TestDirector",
Storyline = "TestStoryline",
ImageUrl = "TestImageUrl",
Genre = "Comedy"
};
var collectionMovieViewModels = new List<MovieViewModel>() { movieOne, movieTwo };
var mappingProviderMock = new Mock<IMappingProvider>();
mappingProviderMock
.Setup(x => x.MapTo<ICollection<MovieViewModel>>(It.IsAny<List<Movie>>()))
.Returns(collectionMovieViewModels);
using (var actAndAssertContext = new MovieManagementContext(options))
{
var sut = new MovieService(actAndAssertContext, mappingProviderMock.Object);
var movies = await sut.GetLatestMoviesAsync();
Assert.AreEqual(2, movies.Count());
Assert.AreEqual("BestRatedMovieTest", movies.FirstOrDefault().Name);
}
}
I created an empty collection and set the Callback of the method to fill that collection,
var collectionOfMovies = new List<Movie>();
var mappingProviderMock = new Mock<IMappingProvider>();
mappingProviderMock
.Setup(x => x.MapTo<ICollection<MovieViewModel>>(It.IsAny<List<Movie>>()))
.Callback<object>(inputargs => collectionOfMovies = inputargs as List<Movie>);

How to add dynamic values to field injections list with custom trigger to camunda properties panel?

I have two questions here
Is it possible to add dynamic lists values to field injection list input ?
Can I create a trigger for this so this can be initiated from any other input selection say a class selection will populate all fields
I was just looking into FieldInjection.js whether that can be extented for the same
Can someone please provide a hint or direction for this ?
Thanks.
For anyone interested in the answer, I was able to achieve the above goal by changing the set function of the Java Class select input as folllowing
few imports
var extensionElementsHelper = require('../../../../helper/ExtensionElementsHelper'),
elementHelper = require('../../../../helper/ElementHelper')
var CAMUNDA_FIELD_EXTENSION_ELEMENT = 'camunda:Field';
function getExtensionFields(bo) {
return bo && extensionElementsHelper.getExtensionElements(bo, CAMUNDA_FIELD_EXTENSION_ELEMENT) || [];
}
then changing the set function to create extension element and push the field values as :
set: function(element, values, node) {
var bo = getBusinessObject(element);
var type = getImplementationType(element);
var attr = getAttribute(type);
var prop = {}
var commands = [];
prop[attr] = values.delegate || '';
var extensionElements = getExtensionFields(bo);
//remove any extension elements existing before
extensionElements.forEach(function(ele){
commands.push(extensionElementsHelper.removeEntry(getBusinessObject(element), element, ele));
});
if(prop[attr] !== ""){
var extensionElements = elementHelper.createElement('bpmn:ExtensionElements', { values: [] }, bo, bpmnFactory);
commands.push(cmdHelper.updateBusinessObject(element, bo, { extensionElements: extensionElements }));
var arrProperties = ["private org.camunda.bpm.engine.delegate.Expression com.cfe.extensions.SampleJavaDelegate.varOne","private org.camunda.bpm.engine.delegate.Expression com.cfe.extensions.SampleJavaDelegate.varTwo"]
var newFieldElem = "";
arrProperties.forEach(function(prop){
var eachProp = {
name:"",
string:"",
expression:""
}
var type = prop.split(" ")[1].split(".").reverse()[0];
var val = prop.split(" ")[2].split(".").reverse()[0];
eachProp.name = val;
if( type == "String"){
eachProp.string = "${" + val +" }"
}else if( type == "Expression"){
eachProp.expression = "${" + val +" }"
}
newFieldElem = elementHelper.createElement(CAMUNDA_FIELD_EXTENSION_ELEMENT, eachProp, extensionElements, bpmnFactory);
commands.push(cmdHelper.addElementsTolist(element, extensionElements, 'values', [ newFieldElem ]));
});
}
commands.push(cmdHelper.updateBusinessObject(element, bo, prop));
return commands;
}
Cheers !.

How to edit a list of object c# linq to xml

<Team Side="Home" TeamRef="ref123">
<Goal PlayerRef="p1111" Time="10" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p4444" Time="11" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="13" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
<Goal PlayerRef="p7777 Time="17" >
<Assist PlayerRef="p9999">p9999</Assist>
</Goal>
</Team>
public void GetScorer(string side, string OCompetition, string OSeason, string OGameId)
{
try
{
var xDoc = XDocument.Load(test);
var query = from q in xDoc.Descendants("Team")
where (string)q.Attribute("Side") == side
from d in q.Elements("Goal")
select new
{
TeamRef = q.Attribute("TeamRef").Value,
PlayerRef = d.Attribute("PlayerRef").Value,
Time = d.Attribute("Time").Value
};
var count = 0;
foreach (var qq in query)
{
if (side == "Home")
{
if (HomeSlateScorerList[count].PlayerRef != qq.PlayerRef)
{
HomeSlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OSeason, OCompetition, OGameId) });
}
else
{
HomeSlateScorerList[count].Time = HomeSlateScorerList[count].Time + "' ";
}
}
if (side == "Away")
{
AwaySlateScorerList.Add(new Scorer() { PlayerRef = qq.PlayerRef, Time = qq.Time, LastName = GetPlayerNameSlate(qq.PlayerRef, OCompetition, OSeason, OGameId) });
}
count++;
}
}
catch (Exception)
{
// ignored
}
}
I would like to edit a player in a list of players
HomeSlateScorerList = new List<Scorer>();
AwaySlateScorerList = new List<Scorer>();
what I would like to achieve is for e.g. there are two players with the ref of "p7777" so in the list of object I would like to have one player with the playerref of "p7777" so if the player exist the format will be
playerref = "p7777"
Time = 13' 17'
or if one player its
Time = 13'
or if another goal is added to the xml its
Time = 13' 17' 25'
HomeSlateScorerList = HomeSlateScorerList
.GroupBy(s => s.PlayerRef)
.Select(g => new Scorer { PlayerRef = g.Key, Time = string.Join(", ", g.Select(v => v.Time)) })
.ToList();
Thanks to: #SergeyS SergeyS

model item passed into dictionary is of type 'system.Collections.Generic.List'1[System.String]',but dictionary is model B

I am trying to create a create combobox with performcallback, but I got the error. here this error "the model item passed into dictionary is of type 'system.Collections.Generic.Lost'1[System.String]', but this dix=ctionary requires a model item of type 'DIS_iDealer.Models.SalesMonitoringModel'"
I don't know which code exactly I need to paste but this is what I have:
view combobox :
#model DIS_iDealer.Models.SalesMonitoringModel
#Html.DevExpress().ComboBoxFor(m => m.mpmGroupLine.DESCRIPTION, settings =>
{
settings.Name = "Desc_ID_CB";
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Report", Action = "cbPartialCategoryDetail" };
settings.Properties.CallbackPageSize = 50;
settings.Properties.ValueField = "DESCRIPTION";
settings.Properties.TextField = "DESCRIPTION";
settings.Width = 150;
settings.SelectedIndex = 0;
settings.Properties.ClientSideEvents.BeginCallback = "function(s,e){e.customArgs['group_Id'] = Category_Id_CB.GetValue()}";
settings.Properties.ValidationSettings.ErrorTextPosition = ErrorTextPosition.Right;
settings.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithText;
settings.Properties.ValidationSettings.Display = Display.Dynamic;
}).BindList((List<string>)new DIS_iDealer.DataAccess.SalesMonitoringDAC().GetProductGroupDetail(Model.mpmGroupLine.GROUPID).ToList()).GetHtml()
controller :
namespace DIS_iDealer.Controllers
{
public class ReportController : BaseController
{
[HttpGet]
public ActionResult Report_SalesMonitoring_2()
{
SalesMonitoringModel mode = new SalesMonitoringModel();
//MPMPRODUCTGROUPLINE itemB = new MPMPRODUCTGROUPLINE();
/*List<string> mpmCate = mode.GetProductGroup();
if (mpmCate != null)
{
itemB.DESCRIPTION = mode.mpmGroupLine.DESCRIPTION;
}*/
ReportModels modelReport = new ReportModels();
if (TempData["ReportSalesMonitoring2"] != null)
{
modelReport = (ReportModels)TempData["ReportSalesMonitoring2"];
string reportParam = string.Empty;
foreach (string item in modelReport.ParameterReport)
{
reportParam += item;
}
ViewBag.IframeURL = modelReport.WebURL + reportParam;
}
return View(mode);
}
[ValidateInput(false)]
public ActionResult cbPartialCategoryDetail(string group_Id)
{
//SalesMonitoringModel model = new SalesMonitoringModel();
SalesMonitoringDAC model = new SalesMonitoringDAC();
List<string> itemDetail = model.GetProductGroupDetail(group_Id);
return PartialView("_cbPartialCategoryDetail", itemDetail);
}
}
}
Please let me know if you need more info. Thanks.

How to add forreign key fields like it happens in django admin site?

Actually am trying to add a foreign key field in my form like how it happens in django admin site . When you click on the green " + " button it opens up a new pop up window where you add the respective field .
My models are like :
class DealType(models.Model):
label = models.CharField(max_length = 100)
def __unicode__(self):
return self.label
class Deal(models.Model):
label = models.ForeignKey(DealType, blank = True, null = True)
.
.
.
And i want to add DealType while i fill up my DealForm .
I think you have to create a seperate view to create a DealType.
In your DealForm you add a link to open that view.
...
I took a look at an admin page from a project of mine.
html
<img src="/static/admin/img/admin/icon_addlink.gif" width="10" height="10" alt="Add Another"/>
Javascript
taken from
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"> </script>
function showAddAnotherPopup(triggeringLink) {
var name = triggeringLink.id.replace(/^add_/, '');
name = id_to_windowname(name);
href = triggeringLink.href
if (href.indexOf('?') == -1) {
href += '?_popup=1';
} else {
href += '&_popup=1';
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
This opens a new window with the view with the add form.
This view should add the DealType and then close the window using the following function also found in the same javascript file
function dismissAddAnotherPopup(win, newId, newRepr) {
// newId and newRepr are expected to have previously been escaped by
// django.utils.html.escape.
newId = html_unescape(newId);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
if (elem.nodeName == 'SELECT') {
var o = new Option(newRepr, newId);
elem.options[elem.options.length] = o;
o.selected = true;
} else if (elem.nodeName == 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
} else {
var toId = name + "_to";
elem = document.getElementById(toId);
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
This is just backtracked from the admin panel but it should get you started.
...
Found a guide that walks you through the process here which probably explains alot better. (havn't read it)