I have seen many examples that claim to solve this issue but none of them address that the controller and view are in 2 different places. This is confusing to deal with for myself and I suspect some other ASP newbies.
NOTE: I am NOT coming from webforms. I have never used webforms nor do I intend to. Please read the question carefully.
@model IEnumerable<CovidAppV5.ViewModel.COVIDvm>
@{
ViewBag.Title = "Index";
}
<meta name="viewport" content="width=device-width" />
<h2>Report</h2>
<asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server">
</asp:GridView>
public ActionResult Index(string Name, string Phone1)
{
//System.Diagnostics.Debug.WriteLine(Phone1);
List<COVIDvm> VMlist = new List<COVIDvm>(); // to hold list of forms
var covidQuery = (from form in db.Case_Log
where form.Name == Name
join eForm in db.Emergency_Leave on form.Name equals eForm.Name
select new {form.Name, form.Phone1, eForm.OrgNumber, eForm.UnableToTelework, eForm.CaringForMinor}).ToList();
GridView.DataSource = covidQuery; //covidQuery is already a list
GridView.Databind();
foreach (var item in covidQuery)
{
COVIDvm objcvm = new COVIDvm(); // ViewModel
objcvm.Name = item.Name;
objcvm.Phone1 = item.Phone1;
objcvm.OrgNumber = item.OrgNumber;
objcvm.UnableToTelework = item.UnableToTelework;
objcvm.CaringForMinor = item.CaringForMinor;
VMlist.Add(objcvm);
}
return View(VMlist);
}
In the controller you can ignore the VMList stuff; that is for displaying a table that works now, but I don't want to use once the gridview is working.
My issue is that these lines in the controller do not work:
GridView.DataSource = covidQuery; //covidQuery is already a list
GridView.Databind();
resulting in this error from GridView:
and this error for DataSource:
But I'm not sure how to get covidQuery to the view in order to do this. I could pass covidQuery like this:
return View(covidQuery);
But then how do I access it in the View?
If there is a different way to do this that is better by all means let me know.
The reason that I want to use the gridview is because depending on the result of the query some columns will not be necessary so the grid needs to generate with a variable number of columns.
I think you are coming from asp.net webforms developer.
In asp.net mvc you can not use gridview as webforms, In MVC you need to use Table tr td format and create loop through each item in @Model in your case.
like
<table>
<thead>
<th>Name </th>
<th>Phone1</th>
</thead>
<tbody>
@foreach(var itm in Model)
{
<tr>
<td>@itm.Name</td>
<td>@itm.Phone1</td>
</tr>
}
<tbody>
</table>
And also MVC is not tightly coupled, You need to use javascript or any other client scripting language to communicate with controller.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.