Category Archives: Linq

Linq

[RESOLVED]LINQ to Entities, selecting mutiple columns to already declared model getting anonymous type error.

I am trying to fill my `ViewModel` from a few different LINQ queries but I am running into the problem of trying to fill multiple properties from a single LINQ query but I get the error

"invalid anonymous type member declarator. anonymous type members must be declared with a member assignment, simple name or member access"

I have done some searches and founds some posts but they are all about completely filling a `ViewModel` and not just a few properties like I am trying to do. What am I supposed to do to fix this, or am I going about this completely wrong?

using (ForumContext db = new ForumContext())
{
	model.ID = db.yaf_Topic
				.Where(t => t.ForumID == 5)
				.OrderByDescending(t => t.Posted)
				.Select(t => t.PollID.Value).First();

	model = db.yaf_Poll
				.Where(p => p.PollID == model.ID)
				.Select(p => new
				{
					model.Question = p.Question,
					model.IsMultipleChocie = p.AllowMultipleChoices,
					model.ExperationDate = p.Closes
				})
				.First();

	model.Choices = db.yaf_Choice
						.Where(c => c.PollID == model.ID)
						.Select(c => new
						{
							model.Votes.Key = c.Choice,
							model.Votes.Value = c.Votes,
						})
						.ToList();

	model.VotedIPs = db.yaf_PollVote
						.Where(p => p.PollID == model.ID)
						.Select(p => p.RemoteIP)
						.ToList();

	model.VotedUserIDs = db.yaf_PollVote
							.Where(p => p.PollID == model.ID)
							.Select(p => p.UserID)
							.ToList();
}

ViewModel:

public class PollVM
{
	public int ID { get; set; }
	public string Question { get; set; }
	public bool IsMultipleChocie { get; set; }
	public DateTime? ExperationDate { get; set; }
	public KeyValuePair<string, int> Choices { get; set; }
	public List<string> VotedIPs { get; set; }
	public List<int?> VotedUserIDs { get; set; }
}

Here are the issues, I observe in your code

Eagle_f90

.Select(c => new

You are using anonymous type and hence you are getting the error, you need to specify the datatype as below

	model.Choices = db.yaf_Choice
						.Where(c => c.PollID == model.ID)
						.Select new KeyValuePair<string, int>(c.Choice, c.Votes)
						})
						.ToList();

You should make your Choices to be a list of keyvaluepair

public List<KeyValuePair<string, int>> Choices { get; set; }


Eagle_f90

model = db.yaf_Poll		
.Where(p => p.PollID == model.ID) .Select(p => new { model.Question = p.Question, model.IsMultipleChocie = p.AllowMultipleChoices, model.ExperationDate = p.Closes }) .First();

With this step you are overriding your previous step of setting Model.ID. Also you need to change the "new" to something like I mentioned above.

[RESOLVED]Redirecting to different controller on button click

I am working on a very simple CRUD gui and I’m struggling with getting the redirect correct so that it will forward the user to another controller.  Currently it just does nothing.  Below is what i have.

Trying to redirect "Notes" to the NotesModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using Robinson_TestApp.Models; 

namespace Robinson_TestApp.Controllers
{
    public class ProductController : Controller
    {
        private DataTransportDataContext context;
        public ProductController()
        {
            context = new DataTransportDataContext();
        }

        public ActionResult Index()
        {
            IList<ProductModel> ProductList = new List<ProductModel>();
            var query = from Product in context.Products
                        select Product;

            var products = query.ToList();
            foreach (var ProductData in products)
            {
                ProductList.Add(new ProductModel()
                {
                    ID = ProductData.ID,
                    Name = ProductData.Name,
                });
            }
            return View(ProductList);
        }

        public ActionResult Create()
        {
            ProductModel model = new ProductModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(ProductModel model)
        {
            try
            {
                Product prod = new Product()
                {
                    Name = model.Name,
                };
                context.Products.InsertOnSubmit(prod);
                context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        public ActionResult Notes()
        {
            NotesModel model = new NotesModel();
            return RedirectToAction("Index", "NotesController");
        }

        [HttpPost]
        public ActionResult Notes(NotesModel model)
        {
            return RedirectToAction("Index", "NotesController");
        }

        protected override void Dispose(bool disposing)
        {
            context.Dispose();
            base.Dispose(disposing);
        }
    }
}

Here is the NotesController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Robinson_TestApp.Models;

namespace Robinson_TestApp.Controllers
{
    public class NotesController : Controller
    {
        private DataTransportDataContext context;
        
        public NotesController()
        {
            context = new DataTransportDataContext();
        }

        private void CreateNotes(NotesModel model)
        {
            model.Notes = context.Products.AsQueryable<Product>().Select(x => 
                new SelectListItem()
            {
                Text = x.Name,
                Value = x.ID.ToString()
            });
        }

        public ActionResult Index()
        {
            IList<NotesModel> NoteList = new List<NotesModel>();
            var query = from note in context.ProductNotes
                        join product in context.ProductNotes
                        on note.ID equals product.ID
                        select new NotesModel
                        {
                            ID = note.ID,NoteText = note.NoteText, Date = note.CreateDate //Archived = note.Archived
                        };
            NoteList = query.ToList();
            return View(NoteList);
        }

        public ActionResult Details(int ID)
        {
            NotesModel model = context.ProductNotes.Where(x => x.ID == ID).Select(x =>
                                                    new NotesModel()
                                                    {
                                                        ID = x.ID,
                                                        NoteText = x.NoteText,
                                                        Date = x.CreateDate,
                                                        //Archived = x.Archived
                                                    }).SingleOrDefault();
            return View(model);
        }

        public ActionResult Create()
        {
            NotesModel notes = new NotesModel();
            CreateNotes(notes);
            return View(notes);
        }

        [HttpPost]
        public ActionResult Create(NotesModel model)
        {
            try
            {
                ProductModel prod = new ProductModel();
                DateTime date = new DateTime();
                ProductNote note = new ProductNote()                
                {
                    ID = prod.ID,
                    NoteText = model.NoteText,
                    CreateDate = date.Date
                };
                context.ProductNotes.InsertOnSubmit(note);
                context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }
        public ActionResult Edit(int id)
        {
            NotesModel notes = context.ProductNotes.Where(x => x.ID == id).Select(x =>
                                 new NotesModel()
                                 {
                                     ID = x.ID,
                                     NoteText = x.NoteText,
                                     Date = x.CreateDate,
                                 }).SingleOrDefault();

            CreateNotes(notes);
            return View(notes);
        }

        [HttpPost]
        public ActionResult Edit(NotesModel model)
        {
            try
            {
                ProductNote note = context.ProductNotes.Where(x => x.ID == model.ID).Single<ProductNote>();
                note.NoteText = model.NoteText;
                note.CreateDate = model.Date;
                context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        public ActionResult Delete(int id)
        {
            NotesModel model = context.ProductNotes.Where(x => x.ID == id).Select(x =>
                                   new NotesModel()
                                   {
                                       ID = x.ID,
                                       NoteText = x.NoteText,
                                       Date = x.CreateDate,
                                   }).SingleOrDefault();
            return View(model);
        }
        
        [HttpPost]
        public ActionResult Delete(NotesModel model)
        {
            try
            {
                ProductNote note = context.ProductNotes.Where(x => x.ID == model.ID).Single<ProductNote>();
                note.NoteText = model.NoteText;
                note.CreateDate = model.Date;
                context.SubmitChanges();
                note.Archived = true;
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }
    }
}

 

The easiest way is to use TempData to pass model to your Notes controller

        [HttpPost]
        public ActionResult Notes(NotesModel model)
        {
            TempData["Model"] = model;
            return RedirectToAction("Index", "Notes");
        }

Do I need to declare that TempDataDictionary in the Product Model?

public TempDataDictionary TempData { get; set; }

Hi,

No you don’t have to declare it in your model. The tempdata dictionary is just available , but its values only till the next request. Pls see:
http://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).Aspx for further details.

Regards,

Yorrick

Thank you Yorrick, it doesnt appear this is the way I should be doing this.  I need this to work everytime, and currently as I have it written it isnt working at all.  It appears to be redirecting to the index of the controller its currently using vs to
the other controller….  Here is the product controller where I added the TempData function.  I’ve read the msdn link you posted and I’m not sure where I’ve gone wrong!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using Robinson_TestApp.Models;
using Robinson_TestApp.Controllers; 

namespace Robinson_TestApp.Controllers
{
    public class ProductController : Controller
    {
        private DataTransportDataContext context;
        public ProductController()
        {
            context = new DataTransportDataContext();
        }

        public ActionResult Index()
        {
            IList<ProductModel> ProductList = new List<ProductModel>();
            var query = from Product in context.Products
                        select Product;

            var products = query.ToList();
            foreach (var ProductData in products)
            {
                ProductList.Add(new ProductModel()
                {
                    ID = ProductData.ID,
                    Name = ProductData.Name,
                });
            }
            return View(ProductList);
        }

        public ActionResult Create()
        {
            ProductModel model = new ProductModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Create(ProductModel model)
        {
            try
            {
                Product prod = new Product()
                {
                    Name = model.Name,
                };
                context.Products.InsertOnSubmit(prod);
                context.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View(model);
            }
        }

        public ActionResult Notes()
        {
            NotesModel model = new NotesModel();
            return RedirectToAction("Index", "NotesController");
        }

        [HttpPost]
        public ActionResult Notes(NotesModel model)
        {
            TempData["Notes"] = model;
            return RedirectToAction("Index", "Notes");
        }

        protected override void Dispose(bool disposing)
        {
            context.Dispose();
            base.Dispose(disposing);
        }
    }
}

Hi th3knick,

Thanks for your post.

th3knick

Do I need to declare that TempDataDictionary in the Product Model?

You didn’t need to declare TempDataDictionary,it’s a property under ControllerBase Class.

Please check this:http://msdn.microsoft.com/en-us/library/system.web.mvc.controllerbase(v=vs.118).aspx

More information about TempData,you can check this:

#What is ViewData, ViewBag and TempData? – MVC options for passing data between current and subsequent request

http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-cplusViewBagplusandplusTem

Hope this can be helpful.

Best Regards,

Eileen

Hi,

Why it isn’t redirecting to your "Notes" Controller, assuming that the controller exist and the name is spelled correctly, I can’t say. Your code sample should work. But What I don’t understand in your code below is why this solution:

        [HttpPost]
        public ActionResult Notes(NotesModel model)
        {
            TempData["Notes"] = model;
            return RedirectToAction("Index", "Notes");
        }

It seems that you post to this method from your view and after that use "TempData" and "RedirectToAction" to transport the model to the "Index" method of the "Notes" Controller. This doesn’t seem to be very economical. Why do you do this this way? Why not
posting directly to the “Notes” controller from the view? That way you only have to do one request instead of two.

Another thing that could be refactored into something more economical ;-) is the following:

public ActionResult Index()
        {
            IList<ProductModel> ProductList = new List<ProductModel>();
            var query = from Product in context.Products
                        select Product;

            var products = query.ToList();
            foreach (var ProductData in products)
            {
                ProductList.Add(new ProductModel()
                {
                    ID = ProductData.ID,
                    Name = ProductData.Name,
                });
            }
            return View(ProductList);
        }

into:

public ActionResult Index()
{
	var productList = (from product in context.Products 
			   select new ProductModel
			   {
				ID = product.ID,
			        Name = product.Name										
			    }).ToList();
	return View(productList);
}

Hope this helps.

Regards,

Yorrick

[RESOLVED]How to fill Lists in ViewModel

 public
class
CustomerFeeViewModel

    {

public
int
CustomerId {
get;
set;
}

public
string
Comments {
get;
set;
}

public
IEnumerable<FeeModel>
Fees {
get;
set;
}

public
IEnumerable<ItemModel>
Items {
get;
set;
}

    }

I have trouble understanding how to fill the Fees and Items list in the ViewModel.

I’m using Linq to Entity. Do you have multiply queries? or can join in one query?

 

You can use include keyword in your linq query

e.g

ObjectQuery<SalesOrderHeader> query =
    context.SalesOrderHeaders.Include("Fees").Include("Items");

What does FeeModel and ItemModel contains and how they are related

So each Fee have a Item associated with it.

and each Customer have Fees against it.

var Custfeeitems = (from e in db.CustomerFeesPayments.Where(f => f.CustomerID = 1)
                           select new CustomerFeeViewModel
                           {

                               CustomerId = e.CustomerId,
                               Fees = e.FeeModel,
                               Comments = e.Comments
                           }.FirstOrDefault<CustomerFeeViewModel>()

alphabeatsco

So each Fee have a Item associated with it.

and each Customer have Fees against it.

I think ViewModel must be like following

    public class CustomerFeeViewModel
    {
        public int CustomerId { get; set; }

        public string Comments { get; set; }

        public IEnumerable<FeeModel> Fees { get; set; }
    }

And query, something like this

how to make working my query

Hi, i got 2 link on created with  

<a href="@Url.RouteUrl("

and the other with

 <li>@Html.RouteLink(

both give me the right routed link :

first link

http://localhost:57959/Magazine/Index/1/styles-inspirations

second link

http://localhost:57959/Magazine/Index/1/styles-inspirations/2/fetes-occasions

but only the second works with the query, why?

if (menuid.HasValue)
             {
               magazines = magazines.Where(r => r.ParentMenuMag.MenuId.Equals(menuid.Value));
            }

            if (submenuid.HasValue)
            {
                magazines = magazines.Where(r => r.ParentSubMenuMag.SubMenuId.Equals(submenuid.Value));
            }

how to make working the first link with my search?

Hi graphic,

Thanks for your post.

grafic.web

<a href="@Url.RouteUrl("

You can use it directly,like this:

    @Url.RouteUrl(...);

More information:

http://www.patridgedev.com/2011/08/22/subtleties-with-using-url-routeurl-to-get-fully-qualified-urls/

Hope it can be helpful.

Best Regards,

Eileen

grafic.web

<a href="@Url.RouteUrl("

@Html.RouteUrl returns a url string and it does not render anchor tag

grafic.web

<li>@Html.RouteLink(

@Html.RouteLink renders a anchor tag with url

Hi,

how should i modify my code of the query to make working this with <a href="@Url.RouteUrl(" ?

if (menuid.HasValue)
             {
               magazines = magazines.Where(r => r.ParentMenuMag.MenuId.Equals(menuid.Value));
            }

with this :

<li>@Html.RouteLink(

my second query works well :


            if (submenuid.HasValue)
            {
                magazines = magazines.Where(r => r.ParentSubMenuMag.SubMenuId.Equals(submenuid.Value));
            }

In fact  the problem is that with <li>@Html.RouteLink( the query above works and not wiht
<a href="@Url.RouteUrl("

How to modifiy this query?

post your routelink and routeurl completely to know how u used

Hi,

here my RouteConfig.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace HairCollection3
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}/{title}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, title = UrlParameter.Optional }
            );

            //localhost/Magazine/menuid/menuname/submenuid/submenuname/ID
            routes.MapRoute(
            name: "MagazineRoute",
            url: "{controller}/{action}/{menuid}/{menuname}/{submenuid}/{submenuname}/{id}",
            defaults: new { controller = "Magazine", action = "Index", menuid = UrlParameter.Optional, menuname = UrlParameter.Optional, submenuid = UrlParameter.Optional, submenuname = UrlParameter.Optional, id = UrlParameter.Optional }
           );


        }
    }
}

And the link

first link (SEARCH QUERY does not work)

<a href="@Url.RouteUrl("MagazineRoute", new { controller = "Magazine", menuid = menu.MenuId, menuname = MenuName.URLFriendly() })" title="@MenuName">@MenuName<i class="fa fa-angle-down"></i></a>   

second link (SEARCH QUERY works wel)l :

<li>@Html.RouteLink(SubMenuName, "MagazineRoute", new { controller = "Magazine", menuid = menu.MenuId, menuname = MenuName.URLFriendly(), submenuid = submenu.SubMenuId, submenuname = SubMenuName.URLFriendly(), })</li>

This is the SEARCH QUERY

if (menuid.HasValue) // First link
             {
               magazines = magazines.Where(r => r.ParentMenuMag.MenuId.Equals(menuid.Value));
            }

            if (submenuid.HasValue)  //second link
            {
                magazines = magazines.Where(r => r.ParentSubMenuMag.SubMenuId.Equals(submenuid.Value));
            }

grafic.web

<a href="@Url.RouteUrl("MagazineRoute", new { controller = "Magazine", menuid = menu.MenuId, menuname = MenuName.URLFriendly() })" title="@MenuName">@MenuName<i class="fa fa-angle-down"></i></a>

I do not find any issue with the above

is the link only for GET or also for POST

Hi, me too, but i don’t know why it does not work with this query :

if (menuid.HasValue)
             {
               magazines = magazines.Where(r => r.ParentMenuMag.MenuId.Equals(menuid.Value));
            }

And the second link, works well with the other query, in fact if i click on it i see only the list of the
ParentSubMenuMag.SubMenuId.Equals(submenuid.Value

How should i change this query to work with this link?

<div>

The problem is that if i change my link :

<a href="@Url.RouteUrl("MagazineRoute", new { controller = "Magazine", menuid = menu.MenuId, menuname = MenuName.URLFriendly() })" title="@MenuName">@MenuName<i class="fa fa-angle-down"></i></a>    

like this :

@Html.RouteLink(MenuName, "MagazineRoute", new { controller = "Magazine", menuid = menu.MenuId, menuname = MenuName.URLFriendly() })</li>

it works perfectly… so the problem, i guess is in the  @Url.RouteUrl(", becaus if i use the
@Html.RouteLink( the query can find the menuid.HasValue

How comes?

</div>

[RESOLVED]Problem Implementing jqGrid in MVC

hi 

i was implementing jqgrid using Trirand.Web.Mvc dll file.

i was refer the example from this link http://www.trirand.net/demo/aspnet/mvc/jqgrid/

but i got errors

this is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System;
using Trirand.Web.Mvc;
using System.Web.UI.WebControls;

namespace JQGridMVCExamples.Models
{
public class OrdersJqGridModel
{
public JQGrid OrdersGrid { get; set; }

public OrdersJqGridModel()
{
OrdersGrid = new JQGrid
{
Columns = new List() // i got error here
{
new JQGridColumn { DataField = "OrderID",
// always set PrimaryKey for Add,Edit,Delete operations
// if not set, the first column will be assumed as primary key
PrimaryKey = true,
Editable = false,
Width = 50 },
new JQGridColumn { DataField = "CustomerID",
Editable = true,
Width = 100 },
new JQGridColumn { DataField = "OrderDate",
Editable = true,
Width = 100,
DataFormatString = "{0:yyyy/MM/dd}" },
new JQGridColumn { DataField = "Freight",
Editable = true,
Width = 75 },
new JQGridColumn { DataField = "ShipName",
Editable = true
}
},
Width = Unit.Pixel(640),
Height = Unit.Percentage(100)
};

OrdersGrid.ToolBarSettings.ShowRefreshButton = true;
}
}
}

Error 1 Using the generic type ‘System.Collections.Generic.List<T>’ requires 1 type arguments C:Usersananth.gDocumentsVisual Studio 2012ProjectsJQGridMVCExamplesJQGridMVCExamplesModelsOrdersJqGridModel.cs 19 31 JQGridMVCExamples

Error 2 Cannot initialize object of type ‘List’ with a collection initializer C:Usersananth.gDocumentsVisual Studio 2012ProjectsJQGridMVCExamplesJQGridMVCExamplesModelsOrdersJqGridModel.cs 20 34 JQGridMVCExamples

any one give me a solution.

hi friends i got a solution

Columns = new List() // change this line
{

}

Columns = List<JQGridColumn>() // like this
{

}

Hi Ananth,

This link may benefit you:

# List<T> Class

http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

Best Regards

Starain Chen

[RESOLVED]Cross tables and Index function on the controller

I’m sure someone has already answered this, but I can’t find the way to do this right.

I am building an MVC 5 app and in one of the columns, we have an int, but what I want to display is the string that comes from another table which corresponds to that column. I know I can use a ViewBag in the Edit or Create functions, but I have the feeling
it won’t work the same way in the index.

Can someone point me in the right direction so I can suss it out?

Thanks in advance….

T

I wrote something in LinqPad which pulls back most of the data I want.

var calls = (from c in Vanguard join r in Van_reason on c.Contact_reason equals r.Valcod where c.Cdts.CompareTo(DateTime.Now.AddDays(-1).ToString("yyyyMMddHHmmss")) >= 0 select new {c.Eid, c.County, c.Cpers, c.Cterm, c.Contact_reason, r.Eng_valcod});

calls.Dump();

But, will this work in the index the way that I want? In there, I’m only using a few of the columns anyway, so that shouldn’t be too big of an issue.

Hi brandrui,

For this requirement, you just need to join these tables’ data. (As you mentioned in your reply)

If you don’t want to get all columns/fields data, you just need get the necessary data by using select.

There is a link that can help you:

# join clause (C# Reference)

http://msdn.microsoft.com/en-us/library/bb311040.aspx

Best Regards

Starain Chen

[RESOLVED]MVC & External Controllers

I am new to MVC so this is a basic question. I have the following two projects:

1) A Web API that was generated with the PLINQO-EF (LINQ to SQL for Entity Framework) template for CodeSmith.

2) An MVC application using Kendo.

Project 2) needs to use the controllers which reside in project 1). My question is how to use the controllers from project 1) without moving the controllers to project 2), i.e. combining the projects.

Note that I can call the Web API from project 2) via PostAsJsonAsync. However, I want to be able to use constructs like

<siteMapNode controller="grid" action="index" title="my title" area="myarea"/>

hufaun

However, I want to be able to use constructs like

<siteMapNode controller="grid" action="index" title="my title" area="myarea"/>

And why you can put this construct?

You should use your other project as an external url in your sitemap

<siteMapNode
title="my
title
"
url="/virtualdirectory/myaread/grid/index"
/>

Hi hufaun,

Since these projects are independent of each other, in my opinion, you can’t able to access the Web API directly, you need to call it through
HttpClient class.

For the siteMapNote, you need to specify the absolute URL. If these projects are under a website, you could refer to
pprasannak’s solution.

Best Regards

Starain Chen

[RESOLVED]Query result that doesn’t make sense (to me)

Hallo , I’m trying  to get  a results base on day of the week  

By doing as follow .

 public PartialViewResult _course()
        {
            int myweekday = 1;

            DateTime dt = DateTime.Now;
            if (dt.DayOfWeek == DayOfWeek.Sunday) myweekday = 1;
            else if (dt.DayOfWeek == DayOfWeek.Monday) myweekday = 2;
            else if (dt.DayOfWeek == DayOfWeek.Tuesday) myweekday = 3;
            else if (dt.DayOfWeek == DayOfWeek.Wednesday) myweekday = 4;
            else if (dt.DayOfWeek == DayOfWeek.Thursday) myweekday = 5;
            else if (dt.DayOfWeek == DayOfWeek.Friday) myweekday = 6;
            else if (dt.DayOfWeek == DayOfWeek.Saturday) myweekday = 7;

            ///for Today
            var _sh = (from c in db.course select c).OrderBy(d => d.daynumber)
                .ThenBy(t => t.Time).Where(w => w.daynumber == myweekday);
            ///for the Next day 
            ///the result here should be 2 (today is sinday and sunday=1)
            ///
            ViewBag.next = (from c in db.course select c).Where(w => w.daynumber == (myweekday + 1))
                            .OrderBy(d => d.daynumber).ThenBy(t => t.Time);

My razor :

 @*the view bag should be null i have only results for sunday and thiis should point to manday*@
                @if (ViewBag.next != null)
                {
                    <h3>tomorrow</h3>
                    foreach (var item in ViewBag.next)
                    {
                        <h3>@ViewBag.Tomorrow</h3>


                        @item.daynumber
                        @item.Writer.Name
                    }
                }

how ever I’m getting the <h3>tomorrow</h3> display  any idea where is my mistake ?

The issue is that your ViewBag may not be null, but may simple exist with 0 items in it. You might want to change the code in your View to check if it is not null and not empty :

@if (ViewBag.next != null && ViewBag.next.Any())
{
       <!-- Omitted for brevity -->
}

You might be able to dramatically simplify your code as you can convert your DayOfWeek value into an integer using the Convert.ToInt32() method as seen below :

public PartialViewResult _course()
{
        // Get the current DateTime
        DateTime dt = DateTime.Now;

        // Since the Day of Week is 0-based, you'll need to increment it by 1
        int myweekday = Convert.ToInt32(dt.DayOfWeek) + 1;


        ///for Today
        var _sh = db.course.Where(w => w.daynumber == myweekday)
                           .OrderBy(d => d.daynumber)
                           .ThenBy(t => t.Time);

        ///the result here should be 2 (today is sinday and sunday=1)
        ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                                .OrderBy(d => d.daynumber)
                                .ThenBy(t => t.Time);
}

thanks a lot Mr. Rion,

i’m getting this Error by using Any

‘System.Data.Entity.Infrastructure.DbQuery<MyProjectName.Models.MyClassName>’ does not contain a definition for ‘Any’

 @if (ViewBag.next != null && ViewBag.next.Any())

Try including a ToList() to actually store a collection of your values in memory instead of a DbQuery :

///the result here should be 2 (today is sinday and sunday=1)
ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                        .OrderBy(d => d.daynumber)
                        .ThenBy(t => t.Time)
                        .ToList();

Rion Williams

Try including a ToList() to actually store a collection of your values in memory instead of a DbQuery :

///the result here should be 2 (today is sinday and sunday=1)
ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                        .OrderBy(d => d.daynumber)
                        .ThenBy(t => t.Time)
                        .ToList();

thanks Rion ,

but no, it’s not null .

john_mm

but no, it’s not null .

Right.

The ToList() call will result in an actual collection of results (in memory) and allow you to use the Any() extension method to check if the collection actually has any elements. You still need the appropriate null check to avoid any null-reference exceptions
when calling the Any() call.

<!-- This ensures that your next collection isn't null and actually contains at least one element -->
@if (ViewBag.next != null && ViewBag.next.Any())
{
     <h3>tomorrow</h3>
     <!-- This will iterate through each value within your collection (which is guaranteed to not be empty) -->
     @foreach (var item in ViewBag.next)
     {
            <h3>@ViewBag.Tomorrow</h3>
            @item.daynumber
            @item.Writer.Name
     }
}
 ViewBag.next = db.course.Where(w => w.daynumber == (myweekday + 1))
                          .OrderBy(d => d.daynumber)
                          .ThenBy(t => t.Time)
                          .ToList();

     @if (ViewBag.next != null && ViewBag.next.Any())
                {
                    <h3>bla</h3>

                    foreach (var item in ViewBag.next)
                    {


                    }

                }

[RuntimeBinderException: 'System.Collections.Generic.List<Hagadol12_8.Models.Course>' does not contain a definition for 'Any']
   CallSite.Target(Closure , CallSite , Object ) +137

john_mm

var stuff = db.course.Where(w => w.daynumber == (myweekday + 1))
                          .OrderBy(d => d.daynumber)
                          .ThenBy(t => t.Time)
                          .ToList();
 

 Validate stuff has stuff in it before working on ViewBag.  Because the viewbag is a dynamic object you’re playing hide and seek with what’s in the View bag.

Separate your concerns by putting all db results into stuff then work on stuffing the Viewbag.  Or better yet don’t even use the viewbag, use strongly typed views.

 

Hi,

john_mm

does not contain a definition for ‘Any’]

If not possible with Any() try with Count

@if (ViewBag.next != null && ViewBag.next.Count > 0)

john_mm

[RuntimeBinderException: 'System.Collections.Generic.List<Hagadol12_8.Models.Course>' does not contain a definition for 'Any']
   CallSite.Target(Closure , CallSite , Object ) +137

The Any() extension method should be available on any IEnumerable collections as long as you are using LINQ either explicitly in your View :

using System.Linq;

or by defining it within the web.config (to be available within your Views) :

<pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Linq" />
      </namespaces>
</pages>

If you are still continuing to encounter issues, you might consider using two of the following options :

  • Consider using the Count() method instead to see if that allows you to perform your check (to see how many values are available in your collection) :
    @if (ViewBag.next != null && ViewBag.next.Count() > 0)
    {
    
    }
  • Or an even easier approach would be to not use the ViewBag at all and actually pass in a strongly typed collection of your values to your View, which would allow you to access them via the Model using :
    // Build your collection of courses
    var courses = db.course.Where(w => w.daynumber == (myweekday + 1))
                           .OrderBy(d => d.daynumber)
                           .ThenBy(t => t.Time)
                           .ToList();
    
    // Pass your courses to your View
    return View("_YourViewName",courses);

    Doing this would allow you to access your courses using a strongly-typed collection instead of a dynamic ViewBag variable as seen below :

    <!-- Define your Model as a List of Course objects -->
    @model List<Hagadol12_8.Models.Course>
    
    <!-- Add your Logic -->
    @if (Model != null && Model.Any())
    {
    
        <!-- Loop through the strongly-typed Course objects in your Model -->
        @foreach (Hagadol12_8.Models.Course course in Model)
        {
    
        }
    }

you are using viewbag as a list data so have to check if there is any element in that list

A circular reference was detected while serializing an object of type

Hi All,

I am using MVC4 and Entity Framework  in my application .

I am serializing my model using JsonSerialize

the code looks like this.

        public static string Serialize(object value)
        {
            
            string formattedItem = JsonConvert.SerializeObject(value, JsonSerializationSettings.Settings);           
           
            formattedItem = formattedItem.Replace(""$type": "", ""type": "");

            return formattedItem;
        }

So I tried using 

 ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore  

   & also tried this 
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,

PreserveReferencesHandling = PreserveReferencesHandling.Objects

When I Use ReferenceLoopHandling, PreserveReferencesHandling  .. there is no circular reference error , but the Json returned is not correct .

How should I solve this problem , Could anyone please suggest .

Thanks

Hi , that link shows the simple structure , but I have a very complex structure of Parent and Child relation ,

Please suggest

Thanks

Hi gowrifor,

For the one-to-many or many-to-many relations, we can’t serialize it directly.

The easy way is that you could use ViewModel or anonymous (select new{}) type, then serialize it.

You also could refer to this article to try to do by yourself:

# Refactoring with LINQ

https://prashantbrall.wordpress.com/tag/entity-framework-and-poco/

There are some links that may benefit you:

# Serializing Entity Framework Objects into JSON Using ASP.Net MVC

http://mytechworld.azurewebsites.net/2010/02/serializing-entity-framework-objects-into-json-using-asp-net-mvc/

# JavaScriptSerializer circular reference when using ScriptIgnore

http://stackoverflow.com/questions/14569207/javascriptserializer-circular-reference-when-using-scriptignore

Best Regards

Starain Chen

[RESOLVED]Always filtering Index View on Bool Entity / Displaying only a subset of data

I would like to have the index view (code below) always filter the data on a bool entitiy so that only a subset of the database displays – not the entire database.

If anyone could point me in the right direction, I would appreciate it.

Index.cshtml

@model PagedList.IPagedList<GenericWebApplication.Models.Class_EntitySet01>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />

@{
    ViewBag.Title = "Class_EntitySet01";
}

<h2>Class_EntitySet01</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@using (Html.BeginForm("Index", "Class_EntitySet01", FormMethod.Get))
{
    <p>
        Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
    </p>
}

<table>
    <tr>
        <th>
            @Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th>
            First Name
        </th>
        <th>
            @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm, currentFilter = ViewBag.CurrentFilter })
        </th>
        <th></th>
    </tr>

        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity01)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity02)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Property_Entity21)
        </td>

        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.ID })
        </td>
    </tr>
}

</table>

<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
    new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

Class_EntitySet01Controller.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using GenericWebApplication.Models;
using GenericWebApplication.DAL;
using PagedList;
using System.Data.Entity.Infrastructure;

namespace GenericWebApplication.Controllers
{
    public class Class_EntitySet01Controller : Controller
    {
        private GenericWebApplicationContext db = new GenericWebApplicationContext();

        // GET: /Class_EntitySet01/
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;           
            
            
            var class_entityset01s = from s in db.Class_EntitySet01s
                           select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                class_entityset01s = class_entityset01s.Where(s => s.Property_Entity01.ToUpper().Contains(searchString.ToUpper())
                                       || s.Property_Entity02.ToUpper().Contains(searchString.ToUpper()));
            }
            
            switch (sortOrder)
            {
                case "name_desc":
                    class_entityset01s = class_entityset01s.OrderByDescending(s => s.Property_Entity01);
                    break;
                case "Date":
                    class_entityset01s = class_entityset01s.OrderBy(s => s.Property_Entity21);
                    break;
                case "date_desc":
                    class_entityset01s = class_entityset01s.OrderByDescending(s => s.Property_Entity21);
                    break;
                default:
                    class_entityset01s = class_entityset01s.OrderBy(s => s.Property_Entity01);
                    break;
            }

            int pageSize = 3;
            int pageNumber = (page ?? 1);

            return View(class_entityset01s.ToPagedList(pageNumber, pageSize));
        }

        // GET: /Class_EntitySet01/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Class_EntitySet01/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Property_Entity01,Property_Entity02,Property_Entity21")] Class_EntitySet01 class_entityset01)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Class_EntitySet01s.Add(class_entityset01);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // POST: /Class_EntitySet01/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "ID,Property_Entity01,Property_Entity02,Property_Entity21")] Class_EntitySet01 class_entityset01)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(class_entityset01).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(class_entityset01);
        }

        // GET: /Class_EntitySet01/Delete/5
        public ActionResult Delete(int? id, bool? saveChangesError = false)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator.";
            }
            Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
            if (class_entityset01 == null)
            {
                return HttpNotFound();
            }
            return View(class_entityset01);
        }

        // POST: /Class_EntitySet01/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            try
            {
                Class_EntitySet01 class_entityset01 = db.Class_EntitySet01s.Find(id);
                db.Class_EntitySet01s.Remove(class_entityset01);
                db.SaveChanges();
            }
            catch (RetryLimitExceededException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                return RedirectToAction("Delete", new { id = id, saveChangesError = true });
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

__________________________________________________________________

Programming Environment:

    Visual Studio 2013
    .NET 4.5
    Entity Framework 6 (EntityFramework 6.1.0 NuGet package)
    OS: Windows 7

Project Based On:
Getting Started with Entity Framework 6 Code First using MVC 5

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application

var class_entityset01s = from s in db.Class_EntitySet01s
                           where s.SomeField == true
                           select s;

Thank you SO much!