I have a database called news and have a column called description, I have two take the Last two entries from table (description column) and display the result as a single string string , ie, want to append the data in the Second last column to the last data. But I am not able to append the text,and deleted the code.
controller
public ActionResult Index()
{
var news = db.News.OrderByDescending(u => u.Id).FirstOrDefault();
return View(news);
}
view
#model Project.Models.News
<a href="#Url.Action("NewsInnerPage", "News")">
<marquee>
<p>
#Html.Raw(Model.Description)
</p>
</marquee>
</a>
sql column
I want to get the value from table last two entries as a single string . can anyone please help me to write the code . how can i append string ???
var news = db.News.OrderByDescending(u => u.Id).Take(2).ToList();
var concatenatedNews = new News {
Description = news[0].Description + news[1].Description
};
or you could do it all in one line
var news = new News { Description = string.Join("", news.OrderByDescending(u => u.Id).Take(2).Select(u => u.Description)) };
Related
I have two tables deal_outlet and vendors_outlet. I am trying to compare a list of outlet_id from deal_outlet table to vendor table but .contain method shows error has some invalid arguments. I really don't understand problem in this code.
public ActionResult Detail_of_deal(int id)
{
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).ToList();
f_model.model4 = db.vendors_outlet.Where(x =>d1.Contains(x.outlet_id)).ToList();
var d = obj.detail_of_image(id,ref model);
return View(f_model);
}
Depending on the goal of the code you could try the following:
public ActionResult Detail_of_deal(int id)
{
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).ToList();
f_model.model4 = db.vendors_outlet.AsEnumerable().Select(x => d1.Contains(x.outlet_id)).ToList();
var d = obj.detail_of_image(id,ref model);
return View(f_model);
}
That should make f_model.model4 a list of all the vendors_outlets that have a matching deal_outlet.id
The Linq Contains method returns true if the list contains the item passed in. You are asking to see if a list of deal_outlet objects contains an int, which obviously it won't.
Instead of projecting a collection of deal_outlets, project a list of integers:
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).Select(x => x.outlet_id);
f_model.model4 = db.vendors_outlet.Where(x =>d1.Contains(x.outlet_id)).ToList();
But logically, that's the same as:
f_model.model4 = db.vendors_outlet.Where(x =>x.outlet_i==id)).ToList();
So it's not clear what you're trying to do.
EDIT
Based on your comments, I believe these are the queries you want:
i am trying to fetch list of outlet_id from deal_outlet table where deal_id equal to id,
var d1 = db.deal_outlet.Where(x => x.deal_id==id).ToList();
Now want to compare this list to vendor_outlet table and fetch those rows where outlet_id from deal_outlet table equals to outlet_id in vendor_outlet table
Get a list of ID's to match:
var ids = d1.Select(x => x.outlet_id).ToList();
And use Contains to see if the list contains any of the IDs from the related table:
f_model.model4 = db.vendors_outlet.Where(vo => ids.Contains(vo.outlet_id))
.ToList();
I'm trying to create a WebGrid which has to be very dynamic. The columns are defined in a list, which I've done like so:
#{
List<WebGridColumn> columns = new List<WebGridColumn>();
foreach (var column in Model.Columns)
{
columns.Add(new WebGridColumn() { ColumnName = column.Name, Header = column.Name });
}
}
#grid.GetHtml(
columns: columns)
All well and good, but the problem I have is with the rows. I'll try and explain...
For this question let's say we have two columns for Name and Address.
I have a collection of row objects, lets say SearchResult objects. A SearchResult contains a Dictionary of any number of attributes, such as Name, Address, Phone, Height, Bra Size, or anything (think of the EAV pattern). I need to access the attributes based on Column Name.
I figured I could do this using format, but I can't seem to figure it out. I want something like this:
columns.Add(new WebGridColumn() { ColumnName = column.Name, Header =
column.Header, Format = #<text>#item.Attributes[column.Name]</text> });
This sort of works but despite creating the format for the separate columns, the rows get populated with only the last column's format. i.e.:
Name Address
1 Main Street 1 Main Street
45 Paradise Av 45 Paradise Av
etc
I think it should work if you leave out the "ColumnName" (superfluous anyway), and also make the dynamic expression a bit more explicit:
columns.Add(
new WebGridColumn() {
Header = column.Header,
Format = (item) => #Html.Raw("<text>" + #item.Attributes[column.Name] + "</text>")
}
);
This issue is related to reference variables. You need to have the Format property in terms of the other properties of the WebGridColumn. This is how I would do it:
#{
List<WebGridColumn> columns = new List<WebGridColumn>();
foreach (var column in Model.Columns)
{
var col = new WebGridColumn();
col.Header = column.Name;
col.Format = (item) => #Html.Raw("<text>" + #item.Attributes[col.Header] + "</text>");
columns.Add(col);
}
}
Using VBNET, MVC 3 and Entity Framework to write my first mvc application - a single user blog application. I am trying to create an archive sidebar that will render something like October 2011 and when the user clicks they will see all posts in october. Right now all my attempts show either duplicate dates - if there are 3 posts in october then i see october 2011 3 times or i only get back one month year combo say oct 2011.
Using groupby with firstordefault i only get back one month yaear combo.
posts = _rdsqlconn.Posts.Where(Function(p) p.PostIsPublished = True).GroupBy(Function(d) d.PostDatePublished).FirstOrDefault
How can i get back unique month year combos with EF?
Additional info
I have that function in my repository. I want to pull the month and year pairs so that i have only one pair for say ocotober even if there are 3 posts in october.
In the repository:
Public Function SelectPostsByDate() As IEnumerable(Of Entities.Post) Implements Interfaces.IPostRepository.SelectPostsByDate
Using _rdsqlconn As New RDSQLConn
Dim posts
posts = _rdsqlconn.Posts.Where(Function(p) p.PostIsPublished = True).GroupBy(Function(p) New With {p.PostDateCreated.Year, p.PostDateCreated.Month}).Select(Function(g) g.Key)
'posts = _rdsqlconn.Posts.Where(Function(p) p.PostIsPublished = True).GroupBy(Function(p) New With {p.PostDatePublished.Value.Year, p.PostDatePublished.Value.Month})
Return posts
End Using
End Function
In my controller i have
Function DateViewPartial() As PartialViewResult
Return PartialView(_postRepository.SelectPostsByDate)
End Function
My partial view has:
#ModelType IEnumerable (of RiderDesignMvcBlog.Core.Entities.Post)
<hr />
<ul style="list-style: none; margin-left:-35px;">
#For Each item In Model
#<li> #Html.ActionLink(item.PostDatePublished.Value.ToString("Y"), "Archives", "Blog", New With {.year = item.PostDatePublished.Value.Year, .month = item.PostDatePublished.Value.Month}, Nothing)</li>
Next
</ul>
In _Layout.vbhtml i call the partial view to render in the sidebar:
<h3>Posts by Date</h3>
#code
Html.RenderAction("DateViewPartial", "Blog")
End Code
I would try this (in C#):
var yearMonths = _rdsqlconn.Posts
.Where(p => p.PostIsPublished)
.GroupBy(p => new { p.PostDatePublished.Year, p.PostDatePublished.Month })
.Select(a => a.Key)
.ToList();
It gives you a list of anonymous objects. Each object has a Year and a Month property - for instance yearMonths[0].Year and yearMonths[0].Month, etc. By applying the Select you actually throw away the elements in each group and you get only a list of group keys (year and month).
Edit
I think, for your purpose the best way is to introduce a "ViewModel" for your sidebar partial view. The ViewModel would describe the year and month group, for instance:
public class ArchiveMonthViewModel
{
public int Year { get; set; }
public int Month { get; set; }
}
Then you don't group with an anonymous type but use this ViewModel type:
var archiveViewModels = _rdsqlconn.Posts
.Where(p => p.PostIsPublished)
.GroupBy(p => new ArchiveMonthViewModel
{
Year = p.PostDatePublished.Year,
Month = p.PostDatePublished.Month
})
.Select(a => a.Key)
.ToList();
archiveViewModels is now a named type: List<ArchiveMonthViewModel> which you can return from your method:
public IEnumerable<ArchiveMonthViewModel> SelectPostsByDate()
{
// code above ...
return archiveViewModels;
}
Now your partial view should be based on a model of type IEnumerable<ArchiveMonthViewModel> (and not IEnumerable<Post>). In your foreach loop (#For Each item In Model) you pull out the ArchiveMonthViewModel elements which are the item in the loop now and then create the action link using item.Year and item.Month.
(Hopefully you can translate this sketch into VB.)
In VB:
Dim groupedPosts = _rdsqlcon.Posts.
Where(Function(p) p.PostIsPublished = True).
GroupBy(Function(p) New With {p.PostDatePublished.Year, p.PostDatePublished.Month }).
Select(g => g.Key)
This just returns the unique Years and Months. If you want to include the Posts for each, try the following:
Dim groupedPosts = _rdsqlcon.Posts.
Where(Function(p) p.PostIsPublished = True).
GroupBy(Function(p) New With {p.PostDatePublished.Year, p.PostDatePublished.Month
From there, you can show the year/month groupings and the associated posts for each:
For Each group In groupedPosts
Console.WriteLine(group.Key.Year & "-" & group.Key.Month)
For Each post In group
Console.WriteLine(post.PostDatePublished)
Next
Next
I have a table that contains a list of EquipmentIDs and another table that has maintenance records.
When the user edits a maintenance record I want there to be a drop down list of all of the equipment IDs from the table.
The dropdown list populates, and it populates with the correct amount of entries, however they all say System.Web.MVC.SelectListItem instead of the value of the ID.
Here is the code that generates the list:
public ActionResult Edit(int id)
{
MaintPerformed maintPerformed = maintPerformedRepository.GetMaintPerformed(id);
IList<EquipmentID> IDs = equipmentIDRepository.GetEquipmentIDAsList();
IEnumerable<SelectListItem> selectEquipList =
from c in IDs
select new SelectListItem
{
//Selected = (c.EquipID == maintPerformed.EquipID),
Text = c.EquipID,
Value = c.Sort.ToString()
};
ViewData["EquipIDs"] = new SelectList(selectEquipList, maintPerformed.ID);
return View(maintPerformed);
}
Here is the entry in the .aspx page for the Dropdown list:
%: Html.DropDownList("EquipIDs") %>
Here is how I am generating the list from the table:
public List<EquipmentID> GetEquipmentIDAsList()
{
return db.EquipmentIDs.ToList();
}
It appears that everything is working correctly with the exception of assigning the text to be displayed in the drop down box.
What am I missing or not thinking correctly about?
SelectList and SelectListItem are actually mutually exclusive. You should be using one or the other. Etiher pass the constructor of SelectList your raw data (IDs) or don't use SelectList at all and just make ViewData["EquipIDs"] your enumerable of SelectListItem. If you go with the latter approach, you will have to tweak your code so that you are setting the selected item in the constructor of SelectListItem (as you had done, but commented out).
Either:
ViewData["EquipIDs"] = new SelectList(IDs, maintPerformed.ID, "EquipID", "Sort");
Or:
IEnumerable<SelectListItem> selectEquipList =
from c in IDs
select new SelectListItem
{
Selected = c.EquipID == maintPerformed.EquipID,
Text = c.EquipID,
Value = c.Sort.ToString()
};
ViewData["EquipIDs"] = selectEquipList;
My problem is pretty simple. Lets say I have a dropdown with users.
in the database i have 3 fields for my user table:
user_id
user_name
user_firstname
in my MVC app i want to link those users to projects. so thats why i want the dropdown.
now, i want to have a selectlist, with the ID as the value, and the firstname AND lastname to be the 'text'
SelectList sl = new SelectList(users, "user_id", "user_name");
now how do i get the first name also in the text? this should be fairly easy, but seems it isnt...
Use LINQ to transform your list of users into a list of SelectListItem.
var selectOptions =
from u in yourUserQuery
select new SelectListItem {
Value = u.user_id,
Text = u.user_firstname + " " + u. user_name
};
You can then convert that to a SelectList however you see fit. I personally like to define a .ToSelectList() extension method for IEnumerable<SelectListItem>, but to each his own.
You need to build a list from your database in the format you need. Here is what I did after my database read into a DataTable,
IList<UsrInfo> MyResultList = new List<UsrInfo>();
foreach (DataRow mydataRow in myDataTable.Rows)
{
MyResultList.Add(new UsrInfo()
{
Usr_CD = mydataRow["USR_NR"].ToString().Trim(),
Usr_NA = mydataRow["USR_NA_LAST"].ToString().Trim() + " , " +
mydataRow["USR_NA_FIRST"].ToString().Trim()
});
}
return new SelectList(MyResultList, "Usr_CD", "Usr_NA");