I've read all questions related to this question, all videos I could find, and I couldn't find a solution to my problem in any of them.
I've been trying to display data from a SQL view in a .cshtml page using the ASP.NET MVC framework.
This is the code in my controller:
public ActionResult childinfo()
{
var myQuery1 = db.WebChildCaretakerInfo.Where(s => s.CustSSN == Custssn).Select(s => new { FirstName = s.FirstName, age = s.age, program_name = s.program_name });
return View(myQuery1);
}
where WebChildCaretakerInfo is the view I want to get data from.
This is the code inside my cshtml page:
@model IEnumerable<WebProgProject.Models.WebChildCaretakerInfo>
@{Layout = null;}
@{
var childName = "";
var age = 0;
var caretakerName = "";
var caretakerEmail = "";
var caretakerPhone = "";
foreach (var item in Model)
{
childName = @item.FirstName;
age = (int)@item.age;
caretakerName = @item.CaretakerName;
caretakerEmail = @item.email;
caretakerPhone = @item.phone_number;}
}
Note: I'm using ChildName and the other variables in read-only textboxes later in the code.
When I try to execute this page, I get this error in the browser:
The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery
1[<>f__AnonymousType33[System.String,System.Nullable1[System.Int32],System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[WebProgProject.Models.WebChildCaretakerInfo]'.Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery
1[<>f__AnonymousType33[System.String,System.Nullable1[System.Int32],System.String]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[WebProgProject.Models.WebChildCaretakerInfo]'.
I tried removing the header
@model IEnumerable<WebProgProject.Models.WebChildCaretakerInfo>
and executing, I get a different error:
Object does not contain a definition for FirstName in childName = @item.FirstName
which of course is nonsense because it's right here in my WebChildCaretakerInfo.cs file:
namespace WebProgProject.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class WebChildCaretakerInfo
{
public string FirstName { get; set; }
public Nullable<int> age { get; set; }
public string programCode { get; set; }
public string CaretakerName { get; set; }
public string email { get; set; }
public string phone_number { get; set; }
public string program_name { get; set; }
public string SSN { get; set; }
public string CustSSN { get; set; }
}
}
Is there a different way of retrieving data from a SQL view into an ASP.NET MVC application that is different to retrieving data from a SQL table? Because in the same application, I'm retrieving data from tables and it's no problem.