I am trying run a Datastore query to get a list of names and prices. However, I keep getting this error message:
Cannot implicitly convert type 'Google.Cloud.Datastore.V1.DatastoreQueryResults' to 'System.Collections.Generic.List<TestApp.Models.AllSportsStore>'
This is the code I am using:
AllSportsStore.cs Page
public DatastoreDb _db;
[BindProperty]
public List<AllSportsStore> SportsStoreList { get; set; }
public void OnGet()
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "xxxxx.json"));
_db = DatastoreDb.Create("projectid");
Query query = new Query("Sports_db");
IEnumerable<Entity> stores = _db.RunQuery(query).Entities;
SportsStoreList = stores.Select(_ => new AllSportsStore
{
Name = _["Name"].ToString(),
Price = _["Price"].ToString(),
}).ToList();
}
AllSportsStore.cshtml page
#for (var i = 0; i < Model.SportsStoreList.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model.SportsStoreList[i].Name)
</td>
<td>
#Html.DisplayFor(model => model.SportsStoreList[i].Price)
</td>
</tr>
}
This is the image of the datastore
Updated code result based on a comment
As already stated in the comments, you are trying to assign the wrong type to the SportsStoreList property.
Have a model to hold entity details from storage
public class SportsStoreItem {
public string Name { get; set; }
public decimal Price { get; set; }
}
Use the model in the AllSportsStore.cs Page
public class AllSportsStore : PageModel {
private readonly DatastoreDb _db;
public AllSportsStore() {
_db = DatastoreDb.Create("projectid");
}
[BindProperty]
public List<SportsStoreItem> SportsStoreList { get; set; }
public IActionResult OnGet() {
Query query = new Query("Sports_db");
IEnumerable<Entity> stores = _db.RunQuery(query).Entities;
SportsStoreList = stores.Select(_ => new SportsStoreItem {
Name = (string)_["Name"],
Price = (decimal)_["Price"]
}).ToList();
return Page();
}
}
Note how the entities retrieved from the data store db were converted to strongly typed objects.
You should then be able to access the items in the list in the view/page.
#for (var i = 0; i < Model.SportsStoreList.Count; i++) {
<tr>
<td>
#Html.DisplayFor(model => model.SportsStoreList[i].Name)
</td>
<td>
#Html.DisplayFor(model => model.SportsStoreList[i].Price)
</td>
</tr>
}
Related
Out of the 4 tables that I have, 3 contain similar(client,policyno,policytype..) fields but with different data. The other table, however, has very different fields(client,sex,telephone,dob..). I have a search box in my view that makes use of the telephone number to display related records from all the 3 tables. Unfortunately, I am not able to handle the fields of the fourth table. Keeps returning the error
System.IndexOutOfRangeException: 'PolicyNo'
My Model:
public class TableModels
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Client { get; set; }
public string PolicyNo { get; set; }
public short? PolicyType { get; set; }
public string Telephone { get; set; }
//Health
public DateTime? DOB { get; set; }
public string Sex { get; set; }
public string DepMemberNumber { get; set; }
protected TableModels ReadValue(SqlDataReader reader)
{
TableModels obj = new TableModels();
if (reader["ID"] != DBNull.Value)
{
obj.ID = (int)reader["ID"];
}
if (reader["Client"] != DBNull.Value)
{
obj.Client = (string)reader["Client"];
}
if (reader["PolicyNo"] != DBNull.Value)
{
obj.PolicyNo = (string)reader["PolicyNo"];
}
if (reader["PolicyType"] != DBNull.Value)
{
obj.PolicyType = (short)reader["PolicyType"];
}
The error is returned on the Protected TableModel class.
Any advice would be appreciated
View:
#model IEnumerable
#foreach (var item in Model.OrderByDescending(m => m.Client))
{
<tr>
<td>
#Html.DisplayFor(modelitem => item.Client)
</td>
<td>
#Html.DisplayFor(modelitem => item.Telephone)
</td>
<td>
#Html.ActionLink("Details", "Details", new { id = item.Telephone })
</td>
</tr>
}
Controller:
public ActionResult Details(string id)
{
using (MainContext db = new MainContext())
{
if (id == null)
{
return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
}
List<SingleView> x1 = db.SingleViews.Where(a => a.Telephone == id).ToList();
List<SingleViewM> x2 = db.SingleViewMs.Where(a => a.Telephone == id).ToList();
List<SingleViewWst> x3 = db.SingleViewWsts.Where(a => a.Telephone == id).ToList();
List<PensionsView> x4 = db.PensionsViews.Where(a => a.Telephone == id).ToList();
List<Health> x5 = db.Health.Where(a => a.Telephone == id).ToList();
SingleModel objview = new SingleModel();
objview.USSD = x1;
objview.Mombasa = x2;
I want to produce the below list of typed checkbox
When i inspect each checkbox (eg levelOne) i want to see each having a unique ID and name like the below
I have a Service (ReplayService) that provides a list of objects (HierarchyLevels) which will be used to create the list of Checkboxes
public IEnumerable<HierarchyLevels> GetHierarchyLevels()
{
return new List<HierarchyLevels>()
{
new HierarchyLevels{Name="LevelOne",ShortName="L1", IsSelected = false},
new HierarchyLevels{Name="LevelTwo",ShortName="L2", IsSelected = false},
new HierarchyLevels{Name="TLevelThree",ShortName="L3", IsSelected = false},
new HierarchyLevels{Name="LevelFour",ShortName="L4", IsSelected = false},
};
}
My Controller Class uses the List of HierarchyLevels (created by the service) to create a new Object viewModel.HierarchyLevels (In the Model) of type IEnumerable
public ActionResult Index()
{
var vm = new MyViewModel();
PopulateViewModel(vm.viewModel);
return View(viewModel);
}
private void PopulateViewModel(ContentReplayViewModelBase viewModel)
{
var hierarchyLevels = replayService.GetHierarchyLevels();
viewModel.HierarchyLevels = hierarchyLevels.Select(h => new SelectListItem {Text = h.Name, Selected = h.IsSelected}).ToArray();
}
My Model class has defined properties for each checkbox that will be created.
public abstract class ReplayViewModelBase
{
public IEnumerable<SelectListItem> HierarchyLevels { get; set; }
....
....
}
public class ReplayByHierarchyLevels : ReplayViewModelBase
{
public bool levelOne { get; set; }
public bool leveltwo { get; set; }
public bool levelThree { get; set; }
public bool levelFour { get; set; }
.....
.....
}
In my View i an looping through the list of HierarchyLevels and producing a List of checkbox. the problem I'm having is I'm not sure how to loop through the list of objects and assign a unique bool property in the Model. In the code snippet below I'm assigning bool property "levelOne" to all the created checkbox (as a result all have the same ID and Name)
#foreach (var level in Model.ReplayByHierarchyLevels.HierarchyLevels)
{
<tr>
<td>#level.Text</td>
<td>#Html.CheckBox(level.Text, level.Selected)</td>
<td>** #Html.CheckBoxFor(x => x.ReplayByHierarchyLevels.levelOne, Model.ReplayByHierarchyLevels.levelOne = level.Selected)</td>
</tr>
}
personally, I would just bind to the HierarchyLevels, so the checkbox view will be:
#for(int i =0; i < Model.ReplayByHierarchyLevels.HierarchyLevels.Count; i++)
{
<tr>
<td>#Model.ReplayByHierarchyLevels.HierarchyLevels[i].Text</td>
<td>
#Html.CheckBoxFor(m => m.ReplayByHierarchyLevels.HierarchyLevels[i].Selected)
#Html.HiddenFor(m => m.ReplayByHierarchyLevels.HierarchyLevels[i].Text)
#Html.HiddenFor(m => m.ReplayByHierarchyLevels.HierarchyLevels[i].Value)
</td>
</tr>
}
then if you want strong type of access, you could change the view model ReplayByHierarchyLevels to do:
public class ReplayByHierarchyLevels : ReplayViewModelBase
{
// be aware may be null
public bool levelOne { get{return HierarchyLevels.FirstOrDefault(x => x.Text == "levelOne").Selected;} }
// rest the same
}
I currently am pulling a list of url's from a view using Entity Framework 5 and MVC 5. I have the view populating all the links but I need each link to display their 'LinkState' names like in my model so it will output:
Alabama
Georgia
etc.
with the link attached to the LinkState. Instead of the view foreach loop saying State Link. I cant get my model/controlled to pull the correct information.
Repository:
public class LinkRepository
{
private readonly LinkLibrary _entities = new LinkLibrary ();
public LinkRepository()
{
_entities = new LinkLibrary ();
}
public List<LinkModels> RetrieveStateLink(string year)
{
return
_entities.vw_URLLibrary.Where(s => s.YEAR.Equals(year) && s.URL_TYPE.Equals("United States")).Select(m => new LinkModels()
{
UrlLink = m.LinkLocation
}).ToList();
}
}
Model
public class LinkModels
{
public string LinkYear { get; set; }
public string LinkState { get; set; }
public string UrlLink { get; set; }
public string LinkType { get; set; }
public List<string> ListOfUrls{ get; set; }
}
Controller
public ActionResult GetStateLinks()
{
var stateLink = new List<string>();
var model = rr.RetrieveStateLinks("2014").Select(m=> m.UrlLink).ToList();
foreach (var s in model)
{
stateLink.Add(s);
}
var rm = new LinkModels();
rm.ListOfUrls = stateLink;
return View(rm);
}
View
#foreach (var item in Model.StateLinkList)
{
<td>
State Link
</td>
}
Your issue is that you are returning a List of strings as opposed to a list of LinkModels. I updated the repository to return the url and link name
removed some unneccessary code in your controller and updated it to work with a list of LinkObjects. Then updated the view to display the info.
You will have to update your view #model List<LinkModels> instead of #model List<string>
public class LinkRepository
{
private readonly LinkLibrary _entities = new LinkLibrary ();
public LinkRepository()
{
_entities = new LinkLibrary ();
}
public List<LinkModels> RetrieveStateLink(string year)
{
return
_entities.vw_URLLibrary.Where(s => s.YEAR.Equals(year) && s.URL_TYPE.Equals("United States")).Select(m => new LinkModels()
{
LinkState = m.LinkState,
UrlLink = m.LinkLocation
}).ToList();
}
}
public ActionResult GetStateLinks()
{
var stateLink = new List<LinkModels>();
var model = rr.RetrieveStateLinks("2014");
return View(model);
}
#foreach (var item in Model)
{
<td>
#item.LinkState
</td>
}
Controller
public ActionResult GetStateLinks()
{
var model = rr.RetrieveStateLinks("2014");
return View(model);
}
View (change your view model to list of LinkModels)
#foreach (var item in Model)
{
<td>
#item.LinkState
</td>
}
I am trying to populate an HTML table with data from a table in my database. The issue is simply that the HTML table is not getting populated with any data.
Here is the ViewModel:
public class TestViewModel
{
public string MatchedId { get; set; }
public string UnmatchedId { get; set; }
public string Auth { get; set; }
public DateTime CreditDate { get; set; }
public string CreditNumber { get; set; }
public decimal CreditAmount { get; set; }
public DateTime DeniedDate { get; set; }
public int DeniedReasonId { get; set; }
public string DeniedNotes { get; set; }
}
Controller Action:
[HttpPost]
public ActionResult UploadValidationTable(HttpPostedFileBase csvFile)
{
var inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true
};
var cc = new CsvContext();
var filePath = uploadFile(csvFile.InputStream);
var model = cc.Read<Credit>(filePath, inputFileDescription);
try
{
var entity = new Entities();
//model here is the .csv, doesn't have anything to do with this issue
foreach (var item in model)
{
var tc = new TemporaryCsvUpload
{
Id = item.Id,
CreditAmount = item.CreditAmount,
CreditDate = item.CreditDate,
CreditNumber = item.CreditNumber,
DeniedDate = item.DeniedDate,
DeniedReasonId = item.DeniedReasonId,
DeniedNotes = item.DeniedNotes
};
entity.TemporaryCsvUploads.Add(tc);
}
entity.SaveChanges();
System.IO.File.Delete(filePath);
//This is where the database table is getting filled
entity.Database.ExecuteSqlCommand("Insert into CsvReport Select p.Id as MatchedId, case when p.Id is null then t.Id end as UnmatchedId, p.Auth,p.CreditDate, p.CreditNumber,p.CreditAmount, p.DeniedDate,p.DeniedReasonId, p.DeniedNotes from TemporaryCsvUpload t left join PermanentTable p on p.Id = t.Id;");
TempData["Success"] = "Updated Successfully";
}
catch (LINQtoCSVException)
{
TempData["Error"] = "Upload Error: Ensure you have the correct header fields and that the file is of .csv format.";
}
return View("Upload");
}
View:
#model IEnumerable<TestProject.TestViewModel>
#if (Model != null)
{
foreach (var item in Model.Where(x => x.IdMatched != null))
{
<tr>
<td>
#item.MatchedId
</td>
<td>
#item.Auth
</td>
<td>
#item.CreditDate
</td>
<td>
#item.CreditNumber
</td>
<td>
#item.CreditAmount
</td>
<td>
#item.DeniedDate
</td>
<td>
#item.DeniedReasonId
</td>
<td>
#item.DeniedNotes
</td>
</tr>
}
}
It's a little weird because I am populating the database with an SQL command. What am I missing here? Do I need to try and pass it through the controller action? Let me know if you need more information. Thanks!
Edit
I tried to pass the instance through, but I may still be doing it incorrectly:
var testModel = new TestViewModel();
return View("Upload", testModel);
Here is what its padding through:
public class TestViewModel
{
public IEnumerable<Test> Test { get; set; }
}
Made an answer so essentially the view doesn't know what to render you need to pass an actual filled model (in your case an IEnumerable to the view). This can be done using the method:
View("Upload", viewModelList);
Controller.View docs on MSDN
It looks like you are not adding any data to your view model.
If your view model is a collection of Test objects, you need to add some
Test objects to the collection.
var model = new TestViewModel()
{
Test = new List<Test>() { new Test(), new Test(), ... }
}
return View("Upload", model);
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I Have Model Class
namespace Project1.Models
{
public class GetTimesheetList
{
public List<TimesheetModel> GetTimesheetDetails { get; set; }
}
public class TimesheetModel
{
ResLandEntities res = new ResLandEntities();
public int WEEK_CAL_ID { get; set; }
public int COMP_ID { get; set; }
public int RES_ID { get; set; }
public int PROJ_ID { get; set; }
public string DESCR { get; set; }
public int TEXTBOX_WEEK_ID { get; set; }
public int EMP_ID { get; set; }
public int SUN_HRS { get; set; }
public int MON_HRS { get; set; }
public int TUE_HRS { get; set; }
public int WED_HRS { get; set; }
public int THU_HRS { get; set; }
public int FRI_HRS { get; set; }
public int SAT_HRS { get; set; }
public string START_DATE { get; set; }
public string END_DATE { get; set; }
public string IS_DELETED { get; set; }
public string CR_BY { get; set; }
}
}
and In View I Have written like
#model Project1.Models.GetTimesheetList
#using (Html.BeginForm("Timesheet", "Employer", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<table class="list-chiller-record">
#for (int i = 0; i < Model.GetTimesheetDetails.Count; i++)// GETTING NULL REFERENCE HERE.
{
if (i == 0)
{
<tr class="chiller-record-template" style="display: none">
<td>#Html.TextBoxFor(m => m.GetTimesheetDetails[i].SUN_HRS, new { style = "width:50px; height:30px;", #class = "sunhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimesheetDetails[i].MON_HRS, new { style = "width:50px; height:30px;", #class = "monhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimesheetDetails[i].TUE_HRS, new { style = "width:50px; height:30px;", #class = "tuehrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimesheetDetails[i].WED_HRS, new { style = "width:50px; height:30px;", #class = "wedhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimesheetDetails[i].THU_HRS, new { style = "width:50px; height:30px;", #class = "thurhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimesheetDetails[i].FRI_HRS, new { style = "width:50px; height:30px;", #class = "frihrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimesheetDetails[i].SAT_HRS, new { style = "width:50px; height:30px;", #class = "sathrs" })
</td>
</tr>
}
}
///Edited.
and From Controller
public Employer Controller
{
public ActionResult Timesheet()
{
return View();
}
}
What is wrong in this getting like
"Object reference not set to reference of the object"
I am Calling List from Model Class and returning "count" of the elements of the list, it should return no. of the elements in the list, but returning null reference instead. Please help me anyone, How do I Fix it ??
you are not initilzing Model data and returning View with empty Model thats why it is giving you error, because object is not instantiated.
You have to instantiate it like this:
public Employer Controller
{
public ActionResult Timesheet()
{
GetTimesheetList model = new GetTimesheetList();
model.GetTimesheetDetails = new List<TimesheetModel>();
return View(model);
}
}
Model.GetTimesheetDetails is null. You need to create an instance using the new keyword.
The problem is that you reference GetTimesheetDetails without initialising it, so when you do GetTimesheetDetails.Count GetTimesheetDetails is null
Update your controller method as mentioned below :
public Employer Controller
{
public ActionResult Timesheet()
{
return View(new GetTimesheetList{
GetTimesheetDetails = new List<TimesheetModel>()
});
}
}
Note: This will return a new instance of your class GetTimesheetList. It will not give any error to you but it will not go through loop as it does not have any data.
You are not returning model to your view, where as your view accepts one.
Your view has this defined
#model Project1.Models.GetTimesheetList
and in the view you have tried to access this model. The first line where its trying to use it is Model.GetTimesheetDetails.Count since no model is passed Model.GetTimesheetDetails is null and hence it throws exception.
You will need to pass a model to the view something like...
public Employer Controller
{
public ActionResult Timesheet()
{
// get model from somewhere;
return View(model);
}
}
If you need to pass an empty model this will be helpful
public ActionResult Timesheet()
{
var model = new GetTimesheetList();
model.GetTimesheetDetails = new List<TimesheetModel>();
return View(model);
}
but that I doubt will be your case, because with this your for loop would be skipped since
Model.GetTimesheetDetails.Count would now not throw error but be zero and skip the loop.