Correct way to use multiple item in the ActionLink? - asp.net-mvc-3

This is a part of my question which I deleted because its too broad
I created a ActionLink for my blog Archive but I'm having trouble with it because I'm calling multiple items inside it.
This is my codes which return an error message No overload for method ActionLink takes 7 arguments
#model IEnumerable <Project.Models.ArchiveListModel>
#foreach (var item in Model)
{
<br />
#Html.ActionLink(item.AchiveMonth, item.AchiveYear, item.PostCount, "ArchiveBrowse", "Post",
new { AchiveYear = item.AchiveMonth, ArchiveMonth = item.AchiveYear, PostCount = item.PostCount }, null)
}
This is my original codes but doesn't have a link it only gives a list
#foreach (var item in Model)
{
<br />
<li> #System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.AchiveMonth) #item.AchiveYear (#item.PostCount) </li>
}
</fieldset><br/>
output:
January 2013 (1)
February 2013 (1)
December 2012 (4)
Here's how I do it in my controller but I know its not working. T_T
public ActionResult Archive()
{
var archivelst = repository.AchiveList().ToList();
return View(archivelst);
}
//this one below is not working
public ActionResult ArchiveBrowse(string archive)
{
var achivemodel = db.Posts.Include("Posts").Single(a => a.Title == archive);
return View(achivemodel);
}
return View(achivemodel);
My ArchiveRepository
public IQueryable<ArchiveListModel> AchiveList()
{
var ac = from Post in db.Posts
group Post by new { Post.DateTime.Year, Post.DateTime.Month }
into dategroup
select new ArchiveListModel()
{
AchiveYear = dategroup.Key.Year,
AchiveMonth = dategroup.Key.Month,
PostCount = dategroup.Count()
};
return ac;
}
What's the correct way to call multiple items in the view?
What I'm trying here is to view the list of Posts under a specific month and year or something like Blog Archives.
Latest Update(working)
Finally I was able to make it work this is now a working one
Updated ArchiveRepository
public IQueryable<ArchiveListModel> AchiveList()
{
var ac = from Post in db.Posts
group Post by new { Post.DateTime.Year, Post.DateTime.Month }
into dategroup
select new ArchiveListModel()
{
AchiveYear = dategroup.Key.Year,
AchiveMonth = dategroup.Key.Month,
PostCount = dategroup.Count()
};
return ac;
}
Updated Controller
public ActionResult ArchiveBrowse(int AchiveYear, int AchiveMonth, int PostCount)
{
var archivemodel = (from a in db.Posts
where a.DateTime.Year == AchiveYear &&
a.DateTime.Month == AchiveMonth
select a).ToList();
return View(archivemodel);
}
Updated View
#foreach (var item in Model)
{
#Html.ActionLink(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.AchiveMonth) + "" + item.AchiveYear + " (" + item.PostCount + ")",
"ArchiveBrowse", "Post", new
{
AchiveYear = item.AchiveYear,
AchiveMonth = item.AchiveMonth,
PostCount = item.PostCount
}, null)
}

It's still not clear to me when you said "call multiple items" so here's my answer, assuming you want to make the list of months years (postcount) into a link. To get this output below
January 2013 (1)
February 2013 (1)
December 2012 (4)
you can concatenate the strings item.AchiveMonth, item.AchiveYear and item.PostCount:
#Html.ActionLink(item.AchiveMonth + " " + item.AchiveYear + " ("+ item.PostCount + ")",
"ArchiveBrowse",
"Post",
new {
AchiveYear = item.AchiveYear,
ArchiveMonth = item.AchiveMonth,
PostCount = item.PostCount },
null)
then in ArchiveBrowse, make sure that your parameters line up properly:
public ActionResult ArchiveBrowse(string AchiveYear, string ArchiveMonth, string PostCount)
{
//Not sure if you want to display posts in the clicked month/year
}

Related

MvcPaging using Ajax

I want to use MvcPaging in a PartialView. I have a search page and I need to paginate the results. So far, only the first page from the results appears - when I am trying to go to page 2 I get in the console a 500 error and nothing happens.
Here are the two actions from controller:
public PartialViewResult SearchResults(string lat, string lng, double? dist)
{
if (Request.IsAjaxRequest())
{
string address = Request["address"];
string latitude = lat;
string longitude = lng;
GeoCoordinate coord = new GeoCoordinate(Double.Parse(latitude, CultureInfo.InvariantCulture), Double.Parse(longitude, CultureInfo.InvariantCulture));
IQueryable<Restaurants> near = (from r in _db.Restaurants select r);
results = new List<Restaurants>();
foreach (Restaurants restaurant in near)
{
double latBD = (double)restaurant.Latitude;
double lngDB = (double)restaurant.Longitude;
if (new GeoCoordinate(latBD, lngDB).GetDistanceTo(coord) <= dist * 1000)
{
results.Add(restaurant);
}
}
return PartialView("_SearchResult", results.ToPagedList(0, 2));
}
return PartialView("Search");
}
public ActionResult PaginationAjax(int? page)
{
int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
return PartialView("_SearchResult", results.ToPagedList(currentPageIndex, 2));
}
And the partial view:
#model IPagedList<Restaurants>
#using MvcPaging
foreach (var item in Model)
{
<blockquote>
<h3>#item.Name</h3>
</blockquote>
}
<div class="pager">
#Html.Pager(Model.PageSize, Model.PageNumber, Model.TotalItemCount, new AjaxOptions { UpdateTargetId = "searchResults" }).Options(o => o.Action("PaginationAjax"))
</div>
Does anyone has any idea what I am doing wrong? Thanks!
EDIT:
Error
GET http://localhost/TakeASeat/Restaurants/PaginationAjax?page=2&X-Requested-With=XMLHttpRequest&_=1431698681795 500 (Internal Server Error)
jQuery.ajaxTransport.send # jquery-2.1.3.js:8625
jQuery.extend.ajax # jquery-2.1.3.js:8161
asyncRequest # jquery.unobtrusive-ajax.js:128
(anonymous function) # jquery.unobtrusive-ajax.js:138
jQuery.event.dispatch # jquery-2.1.3.js:4430
jQuery.event.add.elemData.handle # jquery-2.1.3.js:4116

Asp.net MVC TempData Getting Crossed / Mixed Up

I have used TempData to pass data between controllers. If two users are working on the same page, User2 will get the tempdata value which is created by User1.
Below you can find the code.
Can you please help me to solve this issue.
VDRController.cs
public ActionResult RedirectToCDR(long VslMoveId, long VslVisitId, string VslNm, string ETDDtTmLoc, string statusCd)
{
//List<long> vslIds = new List<long>();
string vslIds = VslMoveId + "," + VslVisitId.ToString() + "," + statusCd;
TempData["VslMoveDetails"] = vslIds;
//DateTime MyDateTime;
//MyDateTime = new DateTime();
var strdatetime = Convert.ToDateTime(ETDDtTmLoc).ToString("dd-MMM-yyyy");
TempData["VslNameETD"] = VslNm + " " + strdatetime;
//return RedirectToAction("Index","VesselVisit");
return Json(Url.Action("Index", "CDR"));
}
CDRController.cs
public ActionResult Index()
{
if (TempData["VslMoveDetails"] != null)
{
string vslIds = TempData["VslMoveDetails"].ToString();
string[] Ids = vslIds.Split(new char[] { ',' });
if (Ids.Length == 3 && Ids[0] != null && Ids[1] != null)
{
ViewBag.VslMove_Id = Ids[0];
ViewBag.VslVisit_Id = Ids[1];
ViewBag.VisitStatus_Cd = Ids[2];
}
}
return View();
}
thanks in advance.
Your pages are being cached by IIS. For MVC applications you will need to add .cshtml to the list of file extensions that are not allowed to cache. Please see the following link for the solution to stop caching. (http://lionsden.co.il/codeden/?p=446)

Blog Archive ASP.NET MVC3

I'm using ASP.NET MVC3. Currently I have a blog. Its working well but the entries are now getting many so I need a archieve to group them monthly. The problem is I dont have an idea how to do it..
I'm thinking its on the datetime but I don't know the logic behind it.. I want to achieve something like this
September 2012 (1)
October 2012 (3)
December 2012 (0)
I would appreciate anyone who would help me. Thanks. :)
You could do it like this. I have the same problem before.
ArchiveRepository
public IQueryable<ArchiveListModel> AchiveList()
{
var ac = from Post in db.Posts
group Post by new { Post.DateTime.Year
, Post.DateTime.Month }
into dategroup
select new ArchiveListModel()
{
AchiveYear = dategroup.Key.Year,
AchiveMonth = dategroup.Key.Month,
PostCount = dategroup.Count()
};
return ac;
}
Controller
public ActionResult ArchiveBrowse(int AchiveYear, int AchiveMonth, int PostCount)
{
var archivemodel = (from a in db.Posts
where a.DateTime.Year == AchiveYear &&
a.DateTime.Month == AchiveMonth
select a).ToList();
return View(archivemodel);
}
View
#foreach (var item in Model)
{
#Html.ActionLink(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item.AchiveMonth) + "" + item.AchiveYear + " (" + item.PostCount + ")",
"ArchiveBrowse", "Post", new
{
AchiveYear = item.AchiveYear,
AchiveMonth = item.AchiveMonth,
PostCount = item.PostCount
}, null)
}

DataTable that has List<string> in it

I'm using Linq to return data from an XML file to a DataTable and that works. But now I'm trying to modify the code to loop through the DataTable. I created a custom class to model the data and have a List in my model. When I loop through the DataTable to display records it displays System.Collections.Generic.List`1[System.String] instead of the actual data. I'm not sure what to search to find the answer.
Snippet:
foreach (DataRow row in tbl.Rows)
{
myList = row["myList"] + ", " + myList;
}
The myList column is the List. I hope this makes sense.
Edited:
public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
(rec,null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
hobbiesList = (List<string>)row["hobbies"];
foreach (var item in hobbiesList)
{
hobbies.Add(item.ToString());
}
hobby = string.Join(", ", hobbies.ToArray());
hobbies.Clear();
I had to do the above to get it to work. I then add hobby to my output array.

LINQ query and lambda expressions

I'm trying to write a LINQ query and am having problems. I'm not sure if lambda expressions are the answer or not but I think they may be.
I have two combo boxes on my form: "State" and "Color".
I want to select Widgets from my database based on the values of these two dropdowns.
My widgets can be in one of the following states: Not Started, In Production, In Finishing, In Inventory, Sold. Widgets can have any color in the 'color' table in the database.
The 'state' combobox has selections "Not Sold," "In Production/Finishing", "Not Started," "In Production," "In Finishing," "In Inventory," "Sold." (I hope these are self-explanatory.)
The 'color' dropdown has "All Colors," and a separate item for each color in the database.
How can I create a LINQ query to select the widgets I want from the database based on the dropdowns?
var WidgetStateChoosen = "Sold";
//var WidgetStateChoosen = "All Widgets";
var WidgetColourChoosen = "Orange";
//var WidgetColourChoosen = "All Colours";
var widgetselected = Widgets.Where
(w =>
( (WidgetStateChoosen == "All Widgets") ? (w.WidgetState != WidgetStateChoosen) : (w.WidgetState == WidgetStateChoosen) )
&&
( (WidgetColourChoosen == "All Colours") ? (w.WidgetColour != WidgetColourChoosen) : (w.WidgetColour == WidgetColourChoosen) )
);
Way more code then I wish, but oh well! I wasnt sure I completely understood your state and selectionstate, but I hope my example is still helpful.
[TestMethod]
public void SelectionTest()
{
var userSelections = GetUserSelections("AllColor", (SelectedState[])Enum.GetValues(typeof(SelectedState)));
var inventory = this.GetInventory();
foreach (var currentSelection in userSelections)
{
var selection = currentSelection;
var result = from item in inventory
where (item.Color == selection.Color || selection.Color == "AllColor") &&
this.GetStates(selection.State).Contains(item.State)
select item;
Console.WriteLine("Item selected for selection: Color:{0} SelectedState:{1}", selection.Color, selection.State);
foreach (var item in result)
{
Console.WriteLine("Item Color:{0};Item State:{1}", item.Color, item.State);
}
Console.WriteLine("");
}
}
private IEnumerable<State> GetStates(SelectedState state)
{
var list = new List<State>();
foreach (State currentState in Enum.GetValues(typeof(State)))
{
if (((int)currentState & (int)state) == (int)currentState)
{
list.Add(currentState);
}
}
return list;
}
private IEnumerable<Item> GetInventory()
{
return new List<Item>()
{
new Item() {State = State.NotStarted, Color = "Blue"},
new Item() {State = State.InFinishing, Color = "Red"},
new Item() {State = State.Sold, Color = "Yellow"},
new Item() {State = State.Sold, Color = "Blue"},
new Item() {State = State.InProduction, Color = "Blue"},
new Item() {State = State.InInventory, Color = "Blue"},
};
}
private IEnumerable<UserSelection> GetUserSelections(String color, IEnumerable<SelectedState> states)
{
var list = new List<UserSelection>();
foreach (var state in states)
{
list.Add(new UserSelection() { Color = color, State = state });
}
return list;
}
[Flags]
private enum State
{
NotStarted = 1,
InProduction = 2,
InFinishing = 4,
InInventory = 8,
Sold = 16
}
private enum SelectedState
{
NotSold = State.InInventory, //Where does it map? I assume INInventory even if it doesnt make much sense
InProductionOrFinishing = State.InProduction | State.InFinishing,
NotStarted = State.NotStarted,
InProduction = State.InProduction,
InFinishing = State.InFinishing,
InInventory = State.InInventory,
Sold = State.Sold,
SomeBizarroTrippleState = State.InProduction | State.Sold | State.NotStarted
}
private class UserSelection
{
public String Color { get; set; }
public SelectedState State { get; set; }
}
private class Item
{
public String Color { get; set; }
public State State { get; set; }
}
var query = db.Widgets;
if (stateFilter == "Not sold")
query = query.Where(w => w.State != WidgetState.Sold);
else if (stateFilter == "In Production/Finishing")
query = query.Where(w => w.State == WidgetState.InProduction || w.State == WidgetState.Finishing);
if (colorFilter != "All colors")
query = query.Where(w => w.Color = colorFilter);
(of course you should have a better way of testing the selected value from the combobox, testing on strings is really bad...)

Resources