I've not been able to find an answer so am posting this. If this has already been answered then please point me in that direction.
I have a class model in MVC as below:
public class SearchModel
{
public int id { get; set; }
public string ActivityName { get; set; }
public string Subject { get; set; }
public string Level { get; set; }
public List<LocationModel> Locations { get; set; }
}
public class LocationModel
{
public int LocationID {get; set;}
public string Location { get; set; }
}
I am trying to populate the Locations list in my code but can't seem to get the code to create an instance of it properly.
I have a List of SearchModel as there are multiple items. This is populating fine by doing the following:
List<SearchModel> items = new List<SearchModel>();
and then looping through the following to populate the model.
SearchModel item = new SearchModel();
item.ActivityName = reader["ActivityName"].ToString();
item.Level = reader["LevelNames"].ToString();
item.Subject = reader["SubjectNames"].ToString();
item.id = Convert.ToInt32(reader["ActivityID"]);
items.Add(item);
How do I add the data to the Locations List in the SearchModel? This will contain multiple records also.
item.Locations = new List<LocationModel>();
you can add some data in it
var myLocationModel = new LocationModel();
myLocationModel.Location = "Africa";
item.Locations.Add(myLocationModel);
Related
I have 2 classes
public class Product
{
public DateTime Date { get; set; }
public string Name { get; set; }
public int Amount { get; set; }
}
public class Campaign
{
public long CampaignId { get; set; }
public string CampaignName { get; set; }
public List<Product> Products { get; set; }
}
Code:
var campaign = new Campaign();
campaign.CampaignId = Item.CampaignId;
campaign.CampaignId = Item.CampaignId;
campaign.CampaignName = Item.CampaignName;
campaign.Products = productList;
campaignList.Add(campaign);
productList.Clear();
When I call productList.Clear(), my "campaign" deletes its campaign.Products.
How can I prevent that from happening?
campaign.Products = new List<Product>(productList);
because campaign.Products is the same reference of productList
they are both pointing to the same list , any action on one will be reflected in the other varialbe
you need to clone (make another copy of the list) by different ways as follwoing
campaign.Products = productList.GetClone();
or
campaign.Products = productList.ToList();
or
campaign.Products.AddRange(productList);
check the following url
https://www.techiedelight.com/clone-list-in-csharp/
How can I fetch and insert data at a specific time in one view in mvc razor view? I mean to fill a dropdown list from the database in create view.
I want to fill the following when I add the subject and cheater models.
department list
semester list
standard list
stream list
cheater model:
namespace firstapp.Models
{
public class chepter
{
[ForeignKey("dip_id")]
public int dipart_id { get; set; }
public int chep_id { get; set; }
public string subject { get; set; }
public string chepter { get; set; }
public List<dipartment> dipartlist { get; set; }
public List<dipartment> stdlist { get; set; }
public List<dipartment> semlist { get; set; }
public List<dipartment> stremlist { get; set; }
}
}
department model:
namespace firstapp.Models
{
public class dipartment
{
public int dip_id { get; set; }
public string dipart { get; set; }
public string std { get; set; }
public string sem { get; set; }
public string strem { get; set; }
}
}
#Html.DropDownListFor(model => model.dipart_id, new SelectList(Model.dipartlist.Select(s => new SelectListItem() { Value = s.dip_id, Selected = false, Text = s.dipart })), "Select")
Change your model so the list property is a selectlist:
public SelectList<dipartment> dipartlist { get; set; }
Then, when you populate the model call a service class method(you might not have a service layer, I just prefer to not have database calls in the controller)
dipartlist = _departmentService.GetAsSelectList();
The GetAsSelectList service method looks like this:
public SelectList GetAsSelectList()
{
return (from d in _context.Set<department>().OrderBy(x => x.dipart)
select new
{
Id = d.dipart_id,
Name = d.dipart
}).ToList();
}
And finally your view:
#Html.DropDownListFor(model => model.dipart_id, Model.dipartlist)
This technique means you don't have linq in either the view or controller. Also as you're only creating the selectlist in one place (the service), you can cache it with MemoryCache to prevent multiple requests for the same data. And as it looks like you're populating 4 selectlists, this might be useful.
I'm currently trying to create an XML based website which has access to a feed URL. The XML feed is queried by adding url parameters to the current URL, and so I am using a form with GET method to add parameters to the URL.
I currently have a property search form which will search for properties within the feed by adding xml parameters to the url like so:
/Sales/?minprice=300000&maxprice=500000
This works perfectly and the correct results are shown to the user. However, if I was to use a filter form which filtered these properties by highest price for example, the feed parameters would be removed when the filter form is submitted. The new URL after the filter would be for example:
/Sales/?priceSort=descending
As you can see, the minprice and maxprice fields have been removed completely, leaving me with unwanted properties.
Currently, to combat this I am using sessions to store the URLs for each page and then combining them to make 1 url. I understand that using sessions within MVC based applications isn't exactly recommended.
So, I'm really just wondering if there is a better way to store the url's rather than using sessions?
Any help would be much appreciated.
Thanks in advance.
SOME CODE SNIPPETS OF THE SITE:
Model and ViewModel
public class ResultsViewModel
{
public PropertyResult[] Property { get; set; }
}
public class PropertyResult
{
public int Count { get; set; }
public int Pid { get; set; }
public int RentalPeriod { get; set; }
public string Price { get; set; }
public string Address { get; set; }
public string NameNumber { get; set; }
public string SA1 { get; set; }
public string SA2 { get; set; }
public string Town { get; set; }
public string City { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public string LocationCode { get; set; }
public string PriceText { get; set; }
public string Primary1 { get; set; }
public string Secondary1 { get; set; }
public string Secondary2 { get; set; }
public string Description { get; set; }
public string Period { get; set; }
public int Bedrooms { get; set; }
public int Receptions { get; set; }
public int Bathrooms { get; set; }
public int Garages { get; set; }
public int Gardens { get; set; }
public bool Featured { get; set; }
public int Views { get; set; }
}
Controller
try
{
var xml = XElement.Load(resultsFeed);
var query = (from props in xml.Descendants("property")
select new PropertyResult
{
// property id
Pid = Convert.ToInt32(props.Attribute("id").Value),
// Rooms Count
Bedrooms = Convert.ToInt32(props.Attribute("bedrooms").Value),
Receptions = Convert.ToInt32(props.Attribute("receptions").Value),
Bathrooms = Convert.ToInt32(props.Attribute("bathrooms").Value),
Gardens = Convert.ToInt32(props.Attribute("gardens").Value),
Garages = Convert.ToInt32(props.Attribute("garages").Value),
// 1 = sales prop, 4 = lettings prop
RentalPeriod = Convert.ToInt32(props.Attribute("rentalperiod").Value),
Period = props.Attribute("period").Value,
// address
Address = props.Element("useAddress").Value,
NameNumber = props.Element("num").Value,
SA1 = props.Element("sa1").Value,
SA2 = props.Element("sa2").Value,
Town = props.Element("town").Value,
City = props.Element("city").Value,
County = props.Element("county").Value,
Postcode = props.Element("postcode").Value,
// location code
LocationCode = props.Element("locationcodes").Value,
Featured = Convert.ToBoolean(props.Attribute("featured").Value),
// description
Description = props.Element("summaryDescription").Value,
// price
Price = props.Attribute("price").Value,
PriceText = props.Element("pricetext").Value,
// images
Primary1 = "http://lb.dezrez.com/Imaging/PictureResizer.ASP?Position=1&AgentId=" + eaid + "&BranchId="+ bid + "&width=1000&Category=Primary&PropertyId=",
Secondary1 = "http://www.dezrez.com/estate-agent-software/ImageResizeHandler.do?&photoID=2&AgentID=1239&BranchID=1976&Width=1000&PropertyId=",
Secondary2 = "http://www.dezrez.com/estate-agent-software/ImageResizeHandler.do?&photoID=3&AgentID=1239&BranchID=1976&Width=1000&PropertyId=",
}).ToArray();
View
I'm currently accessing each node like so:
#Model.Property[i].Gardens
In MVC you need to pass all the needed parameters (or rely in some store as Session, Cache, Db).
So, when sorting, you are just sending the column and order... in this case, you need to post also the filter values.
The correct way to do this, is having a ViewModel with all the filters and sorting parameters... and when you return from filtering or sorting, you can render the current filters.
So, besides filling the filter inputs with the current filters, you should craft the links to take into account all the parameters. For instance: when ordering, you pass also current filters... or if you change the filters you should maintain sortorder passing it on post.
Some code:
Your ViewModel:
public class SalesFilter{
public int? MinPrice {get; set;}
public int? MaxPrice {get; set;}
public int? IdTypeOfSale {get; set;}
...
...
...
public IEnumerable<Sale> FilteredValues {get; set;}
//SelectLists if you need that your filters being DropDownLists
public SelectList TypesOfSales {get; set;}
}
Your Controller:
public ActionResult Sales(){
var model = new SalesFilter();
model.FilteredValues = db.YourSales.Where(/*your init conditions*/);
//set other initial values in your ViewModel
return View(model);
}
[HttpPost]
public ActionResult Sales(SalesFilter filters){
model.FilteredValues = db.YourSales.Where(/*use the conditions of your filter */);
model.TypesOfSales = new SelectList(db.TypesOfSales, "idType", "Name", filter.IdTypeOfSale);
return View(model);
}
Consider using a Domain Model (all your business data, etc.) and separate View Models and extension methods that will transform your domain model to a specific view model and vice versa. Decoupling your business model from your view model using the transform indirection gives you the opportunity to use simple, easy to use view models that fit your view.
I have a method in my repository to retrieve All records for Items
public IQueryable<Item> GetAll()
{
//The following causes a circular reference if you attempt to serialize it via an API call.
IQueryable<Item> items = context.Items.Include(c => c.UserProfile).Include(c => c.UserProfile1).AsQueryable();
return items;
}
This causes issues with Kendo Grid and serialization because of how I am including the foreign tables User Profile twice to be able to get the full name of the user whom created and modified the Item record.
Instead of Include(c => c.UserProfile) is there a way to only include the UserProfile.FullName column?
Today I am handling this in my ViewModel and creating a new subclass (this example is for Locations, not Items):
public class LocationsListViewModel
{
public IEnumerable<LocationsGrid> Locations { get; set; }
public IEnumerable<Facility> Facilities { get; set; }
public IEnumerable<string> AreaOptions { get; set; }
public int LocationCount { get; set; }
public class LocationsGrid
{
public int Id { get; set; }
public string DisplayLocation { get; set; }
public string Area { get; set; }
public string Zone { get; set; }
public string Aisle { get; set; }
public string Bay { get; set; }
public string Level { get; set; }
public string Position { get; set; }
public string Barcode { get; set; }
}
}
and then having to populate that in my Tasks or App Services layer (sits between controller and repository) like this:
viewModel.Locations = from l in locations.ToList()
select new LocationsListViewModel.LocationsGrid
{
Id = l.Id,
DisplayLocation = l.DisplayLocation,
Area = l.Area,
Zone = l.Zone,
Aisle = l.Aisle,
Bay = l.Bay,
Level = l.Level,
Position = l.Position,
Barcode = l.BarcodeValue
};
This seems like a lot of extra code and maintenance for each entity going forward. I'm sure there is a more efficient way to do this.
I typically use a Data-Transfer Object (basically just a class that has the exact data you're looking for, then returning objects of that type from your data-access method.
public IQueryable<ItemSummary> GetAll()
{
IQueryable<ItemSummary> items = context.Items
.Select(c => new ItemSummary {
FirstProfileName = c.UserProfile.FullName,
SecondProfileName = c.UserProfile1.FullName,
ScalarProp1 = c.ScalarProp1,
...
})
.AsQueryable();
return items;
}
I'm not sure if that will work the way you want it to, since I'm not familiar with Kendo Grid and such, but it may be useful.
I am getting some post data from an HTML form. The data that comes up is used to build a TextualReport object. I want to parse the various pieces of form data that come up and populate those parts of my model.
The reason i am not using a model binder is this is a fairly complex object and indices of my lists can be missing (start at 2, skip 3 etc..). I am starting with an existing object, and only replacing the properties that came up in the post.
I have the following object called TextualReport.
public class TextualReport {
public IList<Section> Sections { get; set; }
public IList<string> MiscInputs { get; set; }
public TextualReport(){
Sections = new List<Section>();
MiscInputs = new List<string>();
}
}
public class Section{
public Section(){
Id = Guid.NewGuid();
Blocks = new List<Block>();
}
public Guid Id { get; set; }
public string Heading { get; set; }
public IList<Block> Blocks { get; set; }
}
public class Block{
public Block(){
PreGraphText = new List<string>();
PreGraphInput = new List<string>();
Graphs = new List<Graph>();
PostGraphText = new List<string>();
}
public Guid Id { get; set; }
public string Heading { get; set; }
public IList<string> PreGraphText { get; set; }
public IList<Graph> Graphs { get; set; }
public IList<string> PostGraphText { get; set; }
public IList<string> PreGraphInput { get; set; }
}
public class Graph{
public string Url { get; set; }
public string Caption { get; set; }
}
From my HTML/Razor form, I get a sequence of text strings like the following:
TextualReport.Sections[1].Blocks[0].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[0].Graphs[1].Caption=
TextualReport.Sections[1].Blocks[0].Graphs[2].Caption=
TextualReport.Sections[1].Blocks[0].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[0].PreGraphInput[1]=
TextualReport.Sections[1].Blocks[1].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[1].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[1].PreGraphInput[1]=
TextualReport.Sections[1].Blocks[2].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[2].Graphs[1].Caption=
TextualReport.Sections[1].Blocks[2].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[2].PreGraphInput[1]=
TextualReport.Sections[1].Blocks[3].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[3].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[3].PreGraphInput[1]=
TextualReport.Sections[1].Blocks[4].Graphs[0].Caption=
TextualReport.Sections[1].Blocks[4].PreGraphInput[0]=
TextualReport.Sections[1].Blocks[4].PreGraphInput[1]=
What would be the best approach to populate my existing data with the various pieces that came up in the form post? I get the model from the database, then update based on the new data.