C# ASP.NET MVC view drop down compilation error CS0161 - c#

#model IEnumerable<Calendar.Models.CheckDays
<p>
#using (Html.BeginForm())
{
<table>
<tr>
<th>
#Html.ActionLink("Create New", "Create")
</th>
<th>
#Html.DropDownListFor(model => model.DayOfWeek, htmlAttributes: new { #class = "form-control" })
</th>
<th>
<input type="button" value="Search" />
</th>
</tr>
</table>
}
</p>
<tr>
<th>
#Html.DisplayNameFor(model => model.DayOfWeek)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.DayOfWeek)
</td>
</td>
</tr>
}
I'm trying to create a drop down list so I can filter the the index results but I keep getting an error
"Compiler Error Message: CS1061: 'IEnumerable' does not
contain a definition for 'DayOfWeek' and no extension method
'DayOfWeek' accepting a first argument of type
'IEnumerable' could be found (are you missing a using
directive or an assembly reference?)"
The line that errors out is
Html.DropDownListFor(model => model.DayOfWeek, htmlAttributes: new { #class = "form-control" })".
Do I need to do something in the model or do I have syntax errors?

You misunderstood what first parameter is for. It is to point where selected item should go for. It is for selectedItem variable. Check this blog post: https://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx. You have to create separate class for model with list of elements and variable SelectedDayOfWeek.
Model class:
public class CheckDaysViewModel
{
public IEnumerable<CheckDays> CheckDays {get;set;}
public IEnumerable<SelectListItem> CheckDaysAsSelectedList => this.CheckDays.Select(e => new SelectListItem(e.DayOfWeek, e.DayOfWeek));
public CheckDays SelectedDay {get;set;}
}
cshtml
#model CheckDaysViewModel
<p>
#using (Html.BeginForm())
{
<table>
<tr>
<th>
#Html.ActionLink("Create New", "Create")
</th>
<th>
#Html.DropDownListFor(m => m.SelectedDay, Model.CheckDaysAsSelectedList, null, htmlAttributes: new { #class = "form-control" })
</th>
<th>
<input type="submit" value="Search" />
</th>
</tr>
</table>
}
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(m => m.CheckDays.First().DayOfWeek)
</th>
</tr>
#foreach (var item in Model.CheckDays)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.DayOfWeek)
</td>
</tr>
}
</table>

Related

Multiple partial views in a strongly typed view (ASP.NET MVC5) ? Unable to get relative Path In View

I am having an issue that after saving relative path I cannot get picture in a list, and having error:
CS1061
'IEnumerable<tbl_Advertisement>' does not contain a definition for 'Imagepath' and no extension method 'Imagepath' accepting a first argument of type 'IEnumerable<tbl_Advertisement>' could be found (are you missing a using directive or an assembly reference?) GawadarHubUI C:\Users\Omer FarooQ\Desktop\GawadarHubistan\GawadarHubUI\GawadarHubUI\Areas\Common\Views\SampleViewAD\Index.cshtml
73
Active
This rrror in just view line: #Html.DisplayNameFor(model => Model.ImagePath) that after type Model. I cannot get the the property Name ImagePath, rather it's showing me Extension methods and methods
Controller CODE
using BLL;
using BOL;
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace GawadarHubUI.Areas.Common.Controllers
{
[AllowAnonymous]
public class SampleViewADController : Controller
{
GawadarHubDbEntities db = new GawadarHubDbEntities();
private AdBl objbl;
public SampleViewADController()
{
objbl = new AdBl();
}
// GET: Common/SampleViewAD
[HttpGet]
public ActionResult Index()
{
try
{
var urls = objbl.GetAll().Where(x => x.isapproved == "A").ToList();
return View(urls);
}
catch (Exception e1)
{
TempData["Msg"] = "Approve Failed : " + e1.Message;
return RedirectToAction("Index");
}
}
}
}
View code:
#model IEnumerable<BOL.tbl_Advertisement>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#if (TempData["Msg"] != null)
{
<div class="alert alert-dismissable alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
#TempData["Msg"].ToString()
</div>}
<p>
#Html.ActionLink("SampleViewADController", "urls")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.adtitle)
</th>
<th>
#Html.DisplayNameFor(model => model.adsociety)
</th>
<th>
#Html.DisplayNameFor(model => model.addesc)
</th>
<th>
#Html.DisplayNameFor(model => model.isapproved)
</th>
<th>
#Html.DisplayNameFor(model => model.contactNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.ImagePath)
</th>
<th>
#Html.DisplayNameFor(model => model.price)
</th>
<th>
#Html.DisplayNameFor(model => model.Size)
</th>
<th>
#Html.DisplayNameFor(model => model.tbl_Category.cname)
</th>
<th>
#Html.DisplayNameFor(model => model.tbl_User.useremail)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.adtitle)
</td>
<td>
#Html.DisplayFor(modelItem => item.adsociety)
</td>
<td>
#Html.DisplayFor(modelItem => item.addesc)
</td>
<td>
#Html.DisplayFor(modelItem => item.isapproved)
</td>
<td>
#Html.DisplayFor(modelItem => item.contactNumber)
</td>
<td>
#Html.DisplayFor(model => Model.ImagePath)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
#Html.DisplayFor(modelItem => item.Size)
</td>
<td>
#Html.DisplayFor(modelItem => item.tbl_Category.cname)
</td>
<td>
#Html.DisplayFor(modelItem => item.tbl_User.useremail)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.adid }) |
#Html.ActionLink("Details", "Details", new { id = item.adid }) |
#Html.ActionLink("Delete", "Delete", new { id = item.adid })
</td>
</tr>
}
</table>
Try to replace
#Html.DisplayFor(model => Model.ImagePath)
with
<img src= "#Url.Content(item.ImagePath)" alt="Image" />
Should work.
Your define that your model is a collection:
#model IEnumerable<BOL.tbl_Advertisement>
So every time you write Model., you are referencing this collection.
The collection (IEnumerable<BOL.tbl_Advertisement>) has no property for Imagepath, as the error message tells you.
IEnumerable<tbl_Advertisement> does not contain a definition for Imagepath
Rather, the elements (tbl_Advertisement) of the collection have this property.
This is what Stephen and Igor meant when they wrote that you need to access the Imagepath through the elements of the collection.
Either by looping over the collection:
#foreach (var item in Model) {
<img src= "#Url.Content(item.ImagePath)" alt="Image" />
}
Or for the first element only:
var imagePath = Model.ElementAt(0).ImagePath;

PagedList<T> does not contain a definition for the properties of my Model <T>

I have this partial View as below:
#model IPagedList<Student>
<h2>List of Students</h2>
<div id="studentList">
<div class="pagedList" data-uwa-target="#studentList">
#Html.PagedListPager(Model,page=>Url.Action("Index",new { page }),
PagedListRenderOptions.MinimalWithItemCountText)
</div>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.LastName) //here error
</th>
<th>
#Html.DisplayNameFor(model => model.FirstName) //here error
</th>
<th>
#Html.DisplayNameFor(model => model.City) //here error
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
</tr>
}
</table>
<div class="row">
<div class="col-sm-6" id="slid">
<button id="export" class="btn btn-default btn-primary" onclick="location.href='#Url.Action("ExportInCSVFormat")';return false;">Export Student List in CSV Format</button>
</div>
<div class="col-sm-4" id="excelSlide">
<button id="excelExport" class="btn btn-default btn-success" onclick="location.href='#Url.Action("ExportStudentsInExel")';return false;">Export Student List in Excel Format</button>
</div>
</div>
My Index.cshmtl is :
#model IPagedList<Student>
#{
ViewBag.Title = "Index";
}
#Html.Partial("_Student", Model)
My StudentController is
public ActionResult Index(int page=1)
{
var model = dbAllStudents.Students
.OrderByDescending(p => p.LastName)
.ToPagedList(page, 10);
return View(model);
}
The problem happens to "#Html.DisplayNameFor(model => model.LastName)". It is saying that " IPaged does not contatin a definition for LastName.
I have an idea that the problem is caused because to the Index method of Student Controller I need to add .Select but I am not sure for that. I would really appreciate if someone can help me
It's not working, because overloaded method which you want to use doesn't fit with your interface. It's for IEnumerable<> types. You can access to the first element in the list and it should returns you correct value even if list is empty.
Change your table definition to:
<table class="table">
<tr>
<th>
#Html.DisplayNameFor( => Model[0].LastName)
</th>
<th>
#Html.DisplayNameFor(_ => Model[0].FirstName)
</th>
<th>
#Html.DisplayNameFor(_ => Model[0].City)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(_ => item.LastName)
</td>
<td>
#Html.DisplayFor(_ => item.FirstName)
</td>
<td>
#Html.DisplayFor(_ => item.City)
</td>
</tr>
}
</table>
and everything will be ok.

MVC Partial View Will Not Load

I keep getting an error message along the lines of:
..but this dictionary requires a model item of type..
My view I'm trying to put the partial view into is:
#using TheNovelMachine.Models
#model TheNovelMachine.Models.Account
#{
ViewBag.Title = "Details";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<img id="homeimage" src="~/Image/front-page-book.jpg" alt="The Novel Machine" />
<div id="text" class="col-lg-12">
<h1>Profile</h1>
<div class="col-lg-6 no-gutter">
<h2>#Html.DisplayFor(model => model.Username)</h2>
<h4>#Html.DisplayFor(model => model.FullName)</h4>
<p>#Html.DisplayFor(model => model.Email)</p>
</div>
<div class="col-lg-6 pull-right text-right no-gutter">
<img class="profilepic" src="~/Image/#(Html.DisplayFor(model => model.Username)).jpg" />
</div>
<div class="col-lg-12 no-gutter">
<hr/>
<h4>#Html.DisplayFor(model => model.Username)'s Novels</h4>
#{
Html.RenderPartial("~/Views/Shared/_NovelProfile.cshtml");
}
</div>
</div>
And the Partial View is:
#using System.Web.DynamicData
#using TheNovelMachine.Models
#model IEnumerable<TheNovelMachine.Models.Novel>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.Abstract)
</th>
<th>
#Html.DisplayNameFor(model => model.Privacy)
</th>
<th>
#Html.DisplayNameFor(model => model.AccountId)
</th>
</tr>
#foreach (var item in Model.Where(i => i.AccountId.ToString() == Url.RequestContext.RouteData.Values["id"].ToString())) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Abstract)
</td>
<td>
#Html.DisplayFor(modelItem => item.Privacy)
</td>
<td>
#Html.DisplayFor(modelItem => item.AccountId)
</td>
</tr>
}
</table>
Your partial view is expecting this model (you are declaring it at the top of you partial view)
#model IEnumerable<TheNovelMachine.Models.Novel>
You should pass that model in this line:
#{
Html.RenderPartial("~/Views/Shared/_NovelProfile.cshtml", Model.Novels);
}
That should work, assuming Model.Novels is of this type IEnumerable<TheNovelMachine.Models.Novel> or it can be converted to that type.
Here you have an example with more details, but the idea is the same. If you don't pass this as a parameter, then the partial view can't be constructed (that's why you are getting that error).
MSDN Documentation here for RenderPartial method.
So even though there are other answers as to what you need to do, here is what is actually happening, so you know in the future.
#Html.RenderPartial("_NovelProfile");
would be the same code as:
#Html.RenderPartial("_NovelProfile", Model)

Model Collections Lost When Form Submitted

Using the post request below the model returns null for both the collections yet it correctly returns the boolean attribute. My expectation was that the collections loaded into the model during the get request would persist to the post request. What am I missing?
EDIT: Essentially I am trying to update the list of invoices based on the users selection of a selectlist and a checkbox.
Controller:
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> Index(bool displayFalse = true)
{
InvoiceViewModel invoiceView = new InvoiceViewModel();
var companies = new SelectList(await DbContext.Company.ToListAsync(), "CompanyID", "Name").ToList();
var invoices = await DbContext.Invoice.Where(s => s.Paid.Equals(displayFalse)).ToListAsync();
return View(new InvoiceViewModel { Companies = companies,Invoices = invoices, SelectedCompanyID = 0, DisplayPaid = displayFalse});
}
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Index(InvoiceViewModel model)
{
model.Invoices = await DbContext.Invoice.Where(s => s.CompanyID.Equals(model.SelectedCompanyID) && s.Paid.Equals(model.DisplayPaid)).ToListAsync();
return View(model);
}
Model:
public class InvoiceViewModel
{
public int SelectedCompanyID { get; set; }
public bool DisplayPaid { get; set; }
public ICollection<SelectListItem> Companies { get; set; }
public ICollection<Invoice> Invoices{ get; set; }
}
View:
#model InvoiceIT.Models.InvoiceViewModel
<form asp-controller="Billing" asp-action="Index" method="post" class="form-horizontal" role="form">
<label for="companyFilter">Filter Company</label>
<select asp-for="SelectedCompanyID" asp-items="Model.Companies" name="companyFilter" class="form-control"></select>
<div class="checkbox">
<label>
<input type="checkbox" asp-for="DisplayPaid" />Display Paid
<input type="submit" value="Filter" class="btn btn-default" />
</label>
</div>
<br />
</form>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().InvoiceID)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().CompanyID)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().InvoiceDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().DueDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().Paid)
</th>
<th></th>
</tr>
#foreach (var item in Model.Invoices)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.InvoiceID)
</td>
<td>
#Html.DisplayFor(modelItem => item.CompanyID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.InvoiceDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.DueDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Paid)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.InvoiceID }) |
#Html.ActionLink("Details", "Index", "InvoiceItem", new { id = item.InvoiceID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.InvoiceID })
</td>
</tr>
}
</table>
A form only posts back the name/value pairs of its controls (input, textarea, select). Since the only 2 controls you generate are for the SelectedCompanyID and DisplayPaid properties of your model, then only those properties will be bound when post.
From your comments, what your really wanting to do is to update the table of invoices based on the values of the selected company and the checkbox.
From a performance point of view, the approach is to use ajax to update just the table of invoices based on the value of your controls.
Create a new controller method that return a partial view of the table rows
public PartialViewResult Invoices(int CompanyID, bool DisplayPaid)
{
// Get the filtered collection
IEnumerable<Invoice> model = DbContext.Invoice.Where(....
return PartialView("_Invoices", model);
}
Note you may want to make the CompanyID parameter nullable and adjust the query if your wanting to initially display unfiltered results
And a partial view _Invoices.cshtml
#model IEnumerable<yourAssembly.Invoice>
#foreach(var item in Model)
{
<tr>
<td>#Html.DisplayFor(m => item.InvoiceID)</td>
.... other table cells
</tr>
}
In the main view
#model yourAssembly.InvoiceViewModel
#Html.BeginForm()) // form may not be necessary if you don't have validation attributes
{
#Html.DropDownListFor(m => m.SelectedCompanyID, Model.Companies)
#Html.CheckboxFor(m => m.DisplayPaid)
<button id="filter" type="button">Filter results</button>
}
<table>
<thead>
....
</thead>
<tbody id="invoices">
// If you want to initially display some rows
#Html.Action("Invoices", new { CompanyID = someValue, DisplayPaid = someValue })
</tbody>
</table>
<script>
var url = '#Url.Action("Invoices")';
var table = $('#invoices');
$('#filter').click(function() {
var companyID = $('#SelectedCompanyID').val();
var isDisplayPaid = $('#DisplayPaid').is(':checked');
$.get(url, { CompanyID: companyID, DisplayPaid: isDisplayPaid }, function (html) {
table.append(html);
});
});
</script>
The alternative would be to post the form as your are, but rather than returning the view, use
return RedirectToAction("Invoice", new { companyID = model.SelectedCompanyID, DisplayPaid = model.DisplayPaid });
and modify the GET method to accept the additional parameter.
Side note: Your using the TagHelpers to generate
select asp-for="SelectedCompanyID" asp-items="Model.Companies" name="companyFilter" class="form-control"></select>
I'm not familiar enough with them to be certain, but if name="companyFilter" works (and overrides the default name which would be name="SelectedCompanyID"), then you generating a name attribute which does not match your model property and as a result SelectedCompanyID would be 0 (the default for int) in the POST method.
Appending ToList() to the statement that populates companies is converting the SelectList into a List<T>, which the form will not recognize as a SelectList. Also, by using the dynamic var keyword, you are masking this problem. Try this instead:
SelectList companies = new SelectList(await DbContext.Company.ToListAsync(), "CompanyID", "Name");
In general, try to avoid use of var unless the type is truly dynamic (unknown until runtime).
You put your model data out of form, so it would not submited!
<form asp-controller="Billing" asp-action="Index" method="post" class="form-horizontal" role="form">
<label for="companyFilter">Filter Company</label>
<select asp-for="SelectedCompanyID" asp-items="Model.Companies" name="companyFilter" class="form-control"></select>
<div class="checkbox">
<label>
<input type="checkbox" asp-for="DisplayPaid" />Display Paid
<input type="submit" value="Filter" class="btn btn-default" />
</label>
</div>
<br />
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().InvoiceID)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().CompanyID)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().InvoiceDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().DueDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Invoices.FirstOrDefault().Paid)
</th>
<th></th>
</tr>
#foreach (var item in Model.Invoices)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.InvoiceID)
</td>
<td>
#Html.DisplayFor(modelItem => item.CompanyID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.InvoiceDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.DueDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Paid)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.InvoiceID }) |
#Html.ActionLink("Details", "Index", "InvoiceItem", new { id = item.InvoiceID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.InvoiceID })
</td>
</tr>
}
</table>
</form>
Using a for loop to create the with the companies will make it possible to map back and persist the company values
for(c = 0 ; c < Model.Companies.Count(); c++)
{
<input type='hidden' name='#Html.NameFor(Model.Companies[c].Propery1)' id='#Html.IdFor(Model.Comapnies[c].Propery1)' value='somevalue'>someText />
<input type='hidden' name='#Html.NameFor(Model.Companies[c].Propery2)' id='#Html.IdFor(Model.Comapnies[c].Propery2)' value='somevalue'>someText />
}
this ensures that the list is mapped back as the default model binder expects list to be in ListProperty[index] format

ListBoxFor within IEnumerable model

My model -
...
public string[] _SelectedCountries { get; set; }
and my view -
#using System.Collections.Concurrent
#using Example.Models
#model IEnumerable<Example.Models.vw_SpecialQuestionDefinition>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("Create", "SpecialQuestionDefinition", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Scripts.Render("~/Scripts/SpecialQuestions/Index.js")
<div class="row">
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">Host Country</h4>
</div>
<div class="panel-body">
#*#Html.ListBoxFor("countries", null, new { #class = "sqQuestions" })*#
#Html.ListBoxFor(model => model._SelectedCountries,
new MultiSelectList((List<SelectListItem>)ViewData["countries"], "Value", "Text"),
new { style = "display:block;", #class = "sqQuestions" })
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-12">
<input type="submit" value="Configure" class="btn btn-default"/>
</div>
</div>
<input type="hidden" name="specialQuestionsId" id="specialQuestionsId" value="-1" />
<input type="hidden" name="answerTypesId" id="answerTypesId" value="-1" />
<input type="hidden" name="hostCountrysId" id="hostCountrysId" value="-1" />
<input type="hidden" name="nationalitysId" id="nationalitysId" value="-1" />
<input type="hidden" name="scopeTypesId" id="scopeTypesId" value="-1" />
}
<h4>Special Question Definition</h4>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Question)
</th>
<th>
#Html.DisplayNameFor(model => model.AnswerType)
</th>
<th>
#Html.DisplayNameFor(model => model.LookupTable)
</th>
<th>
#Html.DisplayNameFor(model => model.CountryName)
</th>
<th>
#Html.DisplayNameFor(model => model.NationalityName)
</th>
<th>
#Html.DisplayNameFor(model => model.ScopeType)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Question)
</td>
<td>
#Html.DisplayFor(modelItem => item.AnswerType)
</td>
<td>
#Html.DisplayFor(modelItem => item.LookupTable)
</td>
<td>
#Html.DisplayFor(modelItem => item.CountryName)
</td>
<td>
#Html.DisplayFor(modelItem => item.NationalityName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ScopeType)
</td>
</tr>
}
</table>
and within my controller -
List<SelectListItem> listCountriesSelectListItems = new List<SelectListItem>();
listSpecialQuestionsSelectListItems.Add(new SelectListItem() { Text = "All", Value = "-1" });
foreach (Country co in db.Countries.OrderBy(c => c.CountryName))
{
SelectListItem selectList = new SelectListItem()
{
Text = co.CountryName,
Value = co.CountryId.ToString()
};
listCountriesSelectListItems.Add(selectList);
}
ViewBag.countries = listCountriesSelectListItems;
so when I run the application, I get this error for my ListBoxFor -
'System.Collections.Generic.IEnumerable<Example.Models.vw_SpecialQuestionDefinition>' does not contain a definition for '_SelectedCountries' and no extension method '_SelectedCountries' accepting a first argument of type 'System.Collections.Generic.IEnumerable<Example.Models.vw_SpecialQuestionDefinition>' could be found (are you missing a using directive or an assembly reference?)
And I believe I understand why I get that error. Because I am trying to treat the model within the view as a single object, when in actuality it's of type IEnumerable<Example.Models.vw_SpecialQuestionDefinition>.
How do I get to _SelectedCountries from my model then?
Also, I use an IEnumerable model to populate a table beneath the list box. This list box is outside of the table and has no reason to be inside of it.
EDIT - POSTED entire view.
I am trying to treat the model within the view as a single object,
when in actuality it's of type
IEnumerable.
Your assumption is correct.
How do I get to _SelectedCountries from my model then?
You need a new model and add IEnumerable inside it.
public class SomeViewModel
{
public IEnumerable<vw_SpecialQuestionDefinition>
SpecialQuestionDefinitions { get; set; }
public string[] _SelectedCountries { get; set; }
}
Then foreach will finally like this -
#foreach (var item in Model.SpecialQuestionDefinitions)

Categories

Resources