LINQ: .Select infinite loop - linq

I am getting what appears to be an infinite loop in either LINQ or somehow JQuery. It keeps calling the Controller Method over and over.
Here's my controller method:
public ActionResult Index()
{
// TODO: decide what properties determine a need for User Action (the 'where(s)')
var viewModel = new PriorityTasksViewModel
{
BayOptions = _bayOptionRepository.GetBayOptions()
.Where(x => x.IsActive && !x.SiteVisibilityFlagsOverride).ToList()
.Select(x => new PriorityTasksBayOptionsViewModel()
{
BayGuid = x.BayGUID,
BayNumber = x.BayNumber,
PropertyId = x.PropertyId
})
.ToList(),
Properties = _propertyRepository.GetProperties()
.Where(x => !x.SiteVisibilityFlagsOverride).ToList()
.Select(x => new PriorityTasksPropertiesViewModel()
{
PropertyId = x.PropertyId,
PropertyName = x.Name
})
.ToList()
};
return View("_PriorityTasks", viewModel);
}
If I put a breakpoint in the view, I verify it's looping. What am I missing in my LINQ? I put .ToList() in there to force loading but...
View:
<h6>Properties</h6>
<table class="table">
<tr>
<th>
Name
</th>
</tr>
#foreach (var item in Model.Properties) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.PropertyName)
</td>
</tr>
}
</table>
And the JQuery at the bottom of the _Layout:(it has to show on teh menu of layout)
$(document).ready(function () {
$('#PriorityTasks').load('#Url.Action("Index", "PriorityTask")');
})

Maybe you need return a partial view instead
return PartialView("_PriorityTasks", viewModel);

I think if you want keep a layout you could use a partial view.
Controller:
public ActionResult Images(int? page)
{
int pageNumber = page ?? 1;
page = page ?? 1;
var images = db.image.AsQueryable().OrderBy(x => x.name);
var onePageOfImages = images.ToPagedList(pageNumber, pageSize);
ViewBag.onePageOfImages = onePageOfImages;
return (page == 0)
? PartialView()
: (ActionResult)PartialView("_ImageList");
}
Images.cshtml
#{
ViewBag.Title = "Image List";
}
#using PagedList;
#using PagedList.Mvc;
#Styles.Render("~/Content/PagedList.css")
<h2>Image List</h2>
#DateTime.Now.ToString()
<div id="unobtrusive">
#Html.Partial("_ImageList")
</div>
and _ImageList
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.name)

Related

MVC: Load DropDown From <List>

Trying to load a Drop down and I am getting this error in my view:
Value cannot be null or empty.
Parameter name: name
This is the Controller
static List<AccountList> _acc = new List<AccountList>();
public ActionResult Index()
{
_acc = GetAccounts();
return View(_acc);
}
private List<AccountList> GetAccounts()
{
List<AccountList> temp = new List<AccountList>();
string sSource = "Test";
string sClinicId = "4";
string sStatus = null;
//This is simply retrieving the class from the web service where the list data is stored
ReconUIDataLayer.ClinicAccts retClinicAccts = new ReconUIDataLayer.ClinicAccts();
retClinicAccts = ReconUIDataLayer.UIDataLayer.LoadAccountInfo(sSource, sClinicId, ref sStatus);
temp = (from rows in retClinicAccts.ClinicAccts
select new AccountList
{
Text = rows.AcctName.ToString(),
Value = rows.AcctName.ToString(),
}).ToList();
return temp;
}
This is the View:
#model IEnumerable<C1MvcWebApplication3.Models.AccountList>
#using C1MvcWebApplication3.Models
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table>
<tr><td>#Html.DropDownList("", new SelectList(Model.Select(x => new { Value = x, Text = x}),"AcctName","AcctName"))</td></tr>
</table>
</div>
</body>
</html>
The error is occurring on the helper to create the drop down.
I actually did two things to fix this:
1) just moved the List into my Controller
public ActionResult Index()
{
List<AccountList> _acc = new List<AccountList>();
_acc = GetAccounts();
return View(_acc);
}
I somehow think I didn't need to move the List declaration into the ActionResult and it may bite me later by not making it static.
2) Changed the call in my View
#Html.DropDownList("AccountList",new SelectList(Model, "Value", "Text"),"-Select")
Controller Code
readonly DBDashboardEntities DB = new DBDashboardEntities();// DB Entity Object
public ActionResult Index()
{
//using viewdata
ViewData["SelectDropDown_List"] =new SelectList(DB.tblStudents.ToList(), "studID", "studName");
//using viewbag
ViewBag.SelectDropDownList = new SelectList(DB.tblStudents.ToList(), "studID", "studName");
return View();
}
View Page code: index.cshtml
<tr>
<td>
#Html.DropDownListFor(c => c.studName, new SelectList(
new List<Object>{
new { value = 0 , text = "Rose" },
new { value = 1 , text = "John" },
new { value = 2 , text = "Smith"}
},
"value",
"text", 2))
</td>
<td>
#Html.DropDownListFor(c => c.studID, ViewData["SelectDropDown_List"] as SelectList) #*ViewData requires type casting*#
</td>
<td>
#Html.DropDownList("SelectDropDownList") #*String must be same as ViewBag.SelectDropDownList*#
</td>
</tr>

System.NullReferenceException-NerdDinner Tutorial

I am doing a ASP.NET MVC tutorial. I created a Dinner Controller as well as a index view of Dinner Controller. But, I got an error on my Dinner Index View. The error appears on the for each loop in the following code. But the dinner index view is generated by default. I didnt change any thing.
The code of my Dinner Index View is
#model IEnumerable<NerdDinner.Models.Dinner>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Title
</th>
<th>
Latitude
</th>
<th>
Longitude
</th>
<th>
EventDate
</th>
<th>
ContactPhone
</th>
<th>
Address
</th>
<th>
Country
</th>
<th>
HostedBy
</th>
<th>
Description
</th>
<th></th>
</tr>
#foreach (var item in Model) {//Error appears here
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Latitude)
</td>
<td>
#Html.DisplayFor(modelItem => item.Longitude)
</td>
<td>
#Html.DisplayFor(modelItem => item.EventDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.ContactPhone)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.Country)
</td>
<td>
#Html.DisplayFor(modelItem => item.HostedBy)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.DinnerID }) |
#Html.ActionLink("Details", "Details", new { id=item.DinnerID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.DinnerID })
</td>
</tr>
}
</table>
The code of my Dinner controller is
namespace NerdDinner.Controllers
{
public class DinnerController : Controller
{
IDinnerRepository _repository;
public DinnerController()
{
_repository = new sqlDinnerRepository();
}
public DinnerController(IDinnerRepository repository)
{
_repository = repository;
}
//
// GET: /Dinner/
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
var dinners = _repository.FindAllDinners().Where(x => x.EventDate >= DateTime.Now).ToList();
return Json(dinners);
}
else
{
return View();
}
}
//
// GET: /Dinner/Details/5
public ActionResult Details(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// GET: /Dinner/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Dinner/Create
[HttpPost]
public ActionResult Create(Dinner dinner)
{
try
{
// TODO: Add insert logic here
_repository.AddDinner(dinner);
_repository.Save();
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// GET: /Dinner/Edit/5
public ActionResult Edit(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// POST: /Dinner/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var dinner = _repository.GetDinner(id);
try
{
// TODO: Add update logic here
UpdateModel(dinner, collection.ToValueProvider());
_repository.Save();
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// POST: /Dinner/Delete/5
[HttpPost]
public ActionResult Delete(int id)
{
var dinner = _repository.GetDinner(id);
try
{
// TODO: Add delete logic here
_repository.DeleteDinner(dinner);
_repository.Save();
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
}
}
IDinnerRepository is an interface and sqlDinnerRepository implements it
The code of IDinnerRepository is
namespace NerdDinner.Models
{
public interface IDinnerRepository
{
//Query Methods
IQueryable<Dinner> FindAllDinners();
IQueryable<Dinner> FindUpcomingDinners();
Dinner GetDinner(int id);
//Insert/Delete
void AddDinner(Dinner dinner);
void DeleteDinner(Dinner dinner);
//Persistence
void Save();
}
}
The code of sqlDinnerRepository is
namespace NerdDinner.Models
{
public class sqlDinnerRepository: IDinnerRepository
{
public dbDataContext db;
public sqlDinnerRepository()
{
db = new dbDataContext();
}
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public IQueryable<Dinner> FindUpcomingDinners()
{
return from dinner in db.Dinners
where dinner.EventDate > DateTime.Now
orderby dinner.EventDate
select dinner;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(x => x.DinnerID == id);
}
public void AddDinner(Dinner dinner)
{
db.Dinners.InsertOnSubmit(dinner);
}
public void Save()
{
db.SubmitChanges();
}
public void DeleteDinner(Dinner dinner)
{
db.Dinners.DeleteOnSubmit(dinner);
}
}
}
I have updated my database as well as LINQ data model.
return View();
You didn't pass any model to the view.
Therefore, Model is null.
This action does not send a model to the view when you make a regular GET request.
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
var dinners = _repository.FindAllDinners().Where(x => x.EventDate >= DateTime.Now).ToList();
return Json(dinners);
}
else
{
return View();
}
}
I don't know why default project does this but you can fix the NRE like this:
public ActionResult Index()
{
var dinners = _repository.FindAllDinners().Where(x => x.EventDate >= DateTime.Now).ToList();
if (Request.IsAjaxRequest())
{
return Json(dinners);
}
else
{
return View(dinners);
}
}

Model data is always null when passing it to controller (mvc3 with razor)

I use a callback panel inside a form and when the Combobox Value changes the values of the fields inside the CallbackPanel should be updated accordingly.
My issue is that the model values are always null inside the controller and i do not know why! (model.Documents = null and model.SelectedDocument = null)
It would be great if someone could tell me where my issue is and how to solve it.
Here is my code(edited):
View
#using (Html.BeginForm("Finalize", "DocumentsWaitingApproval", FormMethod.Post, Model))
{
<table>
<tr>
<td>
#Html.DevExpress().ComboBox(settings =>
{
settings.SelectedIndex = 0;
settings.Properties.TextField = "Title";
settings.ClientEnabled = true;
settings.Properties.ClientInstanceName = "CmbBoxFiles";
settings.Properties.EnableClientSideAPI = true;
settings.Properties.ValueType = typeof(int);
settings.Properties.ValueField = "DocumentID";
settings.Name = "CmbBoxFiles";
settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s,e) { cmbBoxFiles_SelectedIndexChanged(s,e); }";
}).BindList(Model.Documents).GetHtml()
</td>
</tr>
</table>
#Html.DevExpress().CallbackPanel(
settings =>
{
settings.Name = "cbpDocWaiting";
settings.CallbackRouteValues = new { Controller = "DocumentsWaitingApproval", Action = "Refresh" };
Controller Methods
[Authorize]
public ActionResult Refresh(DocumentsWaitingApprovalModel model) // model.SelectedDocument is always null
{
}
[Authorize]
public ActionResult Finalize([Bind]DocumentsWaitingApprovalModel model) //model.SelectedDocument is always null
{
return RedirectToAction("Index");
}
}

Validation Issues on Hidden DropDownListFor's ASP.NET MVC3

FINAL EDIT: The problem was that ViewBag.PropName == Model.PropName;
FIX: ViewBag.PropName ===> ViewBag.PropName2
This is my first time posting; I'm new and think I messed up the layout... so sorry!
I encountered some issues with client-side validation for hidden dropdownlistfor's.
I am working with ASP.NET MVC3 and have a lot of hidden ddl on this page.
The validation however, doesn't work for some ddl's.
Has anyone ever had a problem with this before?
These are 2 properties; 1 working, 1 failing
//VALIDATION FAILS
[Required]
[Range(0, 4)]
public int TiresBack { get; set; }
//VALIDATION WORKS
[Required]
[Range(0, 4)]
public int TechnicalState { get; set; }
This is a piece the razor:
<tr>//THIS DOESN'T WORK
<td style="width: 38%;">
#txtFor("tiresBack")
</td>
//This is JQuery Star-Rating.
<td align="center" id="starsTiresBack">
</td>
<td>
#Html.DropDownListFor(model => model.TiresBack, ViewBag.TiresBack as IEnumerable<SelectListItem>, new { style = "display:none;" })
<input class="blueButton" type="button" id="btnBrandRearTires" value="#txtFor("brandTiresBack")" />
<span>#Html.ValidationMessageFor(model => model.TiresBack)</span> <span>#Html.ValidationMessageFor(model => model.BrandRearTires)</span>
</td>
</tr>
//THIS WORKS
<tr>
<td style="width: 38%;">
#txtFor("technicalState")
</td>
<td id="starsTechnicalState" align="center">
</td>
<td>
#Html.DropDownListFor(model => model.TechnicalState, ViewBag.TechState as IEnumerable<SelectListItem>, new { style = "display:none;" })
<input class="blueButton" type="button" id="btnTechnicalStateDescription" value="#txtFor("technicalStateDescriptionButton")" style="display:none;"/>
<span>#Html.ValidationMessageFor(model => model.TechnicalState)</span> <span>#Html.ValidationMessageFor(model => model.TechnicalStateDescription)</span>
</td>
</tr>
EDIT1: Initialised in the controller using this method:
public static List<SelectListItem> CreateDefaultStateList(int? selected = -1)
{
List<SelectListItem> sl = new List<SelectListItem>();
for (int i = -1; i < 5; i++)
{
SelectListItem sli = new SelectListItem();
if (i == 0 || i == -1)
sli.Text = "";
else
sli.Text = i.ToString();
sli.Value = i.ToString();
if (i == selected)
sli.Selected = true;
sl.Add(sli);
}
return sl;
}
EDIT2: The create controller. defaultstatelist is what got returned from the method posted above.
List<SelectListItem> defaultStateList = CreateDefaultStateList();
[Authorize]
public ActionResult Create()
{
FillViewBag();
ViewBag.PropX = defaultStateList;
ViewBag.TiresFront = defaultStateList;
ViewBag.TechState = defaultStateList;
ViewBag.PropY= defaultStateList;
ViewBag.PropZ= defaultStateList;
ViewBag.PropA= defaultStateList;
ViewBag.PropB= defaultStateList;
ViewBag.PropC= defaultStateList;
ViewBag.PropD= defaultStateList;
return View();
}
Typing this I notice the the default value in the method. That could be it...
==> Tried it, wasn't it. Updated code to '-1' as default value now.
The problem was that ViewBag.PropName == Model.PropName;
FIX: Rename ViewBag.PropName to something else like ViewBag.PropName2.

Data annotations don't seem to work

I have a model Contact with data annotation
[Required(ErrorMessage = "Please enter a Contact Name")]
public string ContactName
{ get; set; }
[Required(ErrorMessage = "Please enter a Region")]
public string Region
{ get; set; }
I am passing this model as a list in another model ClientModel
[Required(ErrorMessage = "Please enter a name")]
public string clientname
{get;set;}
Public List<Contact> contact
{get;set;}
Now in my view I am binding my ClientModel
like this
#model MyContact.Models.ClientModel
When I submit the corresponding view only clientname comes with a validation message. There are textboxes which are populated from List<Contact> but they do not validate. I have copied the required scripts in layout and also have added a validation summary. I cannot understand why the validation is not happening.
these are my textboxes
<table border="0" id="tbl2" cellspacing="10" cellpadding="0">
#for (int i = 0; i < Model.ContactList.Count; i++)
{
<tr>
<td>
#Html.CheckBox("chk1", true, new { #class = "BASESAccountTeamChkBoxItem" })
</td>
<td>
#Html.TextBoxFor(m => m.ContactList[i].ContactName, new { style = "width:170px;"})
#Html.ValidationMessageFor((m => m.ContactList[i].ContactName)
</td>
<td>
#Html.TextBoxFor(m => m.ContactList[i].Region, new { style = "width:170px;" })
#Html.ValidationMessageFor((m => m.ContactList[i].ContactName)
</td>
<td>
#Html.TextBoxFor(m => m.ContactList[i].Email, new { style = "width:170px;" })
#Html.ValidationMessageFor((m => m.ContactList[i].Email)
</td>
<td>
#Html.TextBoxFor(m => m.ContactList[i].Phone, style = "width:170px;" })
#Html.ValidationMessageFor((m => m.ContactList[i].Phone)
</td>
<td>
#Html.TextBoxFor(m => m.ContactList[i].Fax, new { style = "width:170px;" })
#Html.ValidationMessageFor((m => m.ContactList[i].Fax)
</td>
</tr>
}
</table>
This is the javascript that will add a new row
+Add New Contact
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
if (table.rows[0].cells[i].innerHTML != "") {
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
}
When i add a new row the validation does not work.I cant know why that is happening
And i have kept my view in #Html.Beginform only. As my view is huge i am not posting the entire code. I also have the scripts in place .Please help
I had this problem a long time ago too, when I started learning ASP.Net MVC3. Here are some tips you can try.
We may be able to help better if you paste your view (or parts of your view) into here as well.
Is your form surrounded by a
#using(Html.BeginForm()){}
snippet?
If it's not, and you're doing the form by hand, you may get unexpected behavior with the MVC Javascript validator.
Are you including the
#Html.ValidationFor()
for each of your text boxes?
And not just a ValidationFor() the list?

Resources