asp.net razor : retrieve data from database - asp.net

I m new in MVC framework. my query is i have to receive data from database sql
database. and display in .cshtml
.plz help....
public ActionResult Index()
{
var model = (from p in am.AMS_Page_Accesses
where p.Role_id == "m"
select new {
p.Name,
p.Id,
p.Link
}).ToList();
var abc= new linkname
{
}
return View(abc);
}
Model
public class linktab
{
public string id { get; set; }
public string Name { get; set; }
public string link { get; set; }
}
public class linkname
{
public List<linktab> menu { get; set; }
}
in .cshtml
#foreach (var a in Model)
{
<div>a.Name</div>
<div>a.Id</div>
<div>a.Link</div>
}

You did not show what exactly is your view's model, according to the error you got it seems you did not specify it at all (using the #model directive).
Try this
public ActionResult Index()
{
var model = (from p in am.AMS_Page_Accesses
where p.Role_id == "m"
select new linktab
{
Id = p.Id,
Link = p.Link,
Name = p.Name
}).ToList();
var abc = new linkname
{
menu = model
}
return View(abc);
}
In your view:
#model linkname
#foreach (var a in Model.menu)
{
<div>a.Name</div>
<div>a.Id</div>
<div>a.Link</div>
}

You're sending an Empty collection change you action like this,
I'm assuming that your view it's strongly typed to the List of linktab
public ActionResult Index()
{
var model = (from p in am.AMS_Page_Accesses
where p.Role_id == "m"
select new linktab{
Name = p.Name,
id = p.Id,
link = p.Link
}).ToList();
return View(model);
}
If it's not the case and your model it's strongly type to the class linkname you should do your action like this
public ActionResult Index()
{
var model = (from p in am.AMS_Page_Accesses
where p.Role_id == "m"
select new linktab{
Name = p.Name,
id = p.Id,
link = p.Link
}).ToList();
linkname abc= new linkname
{
menu = model
}
return View(abc);
}
And you may change the code in your view something like this
#foreach (var a in Model.menu)
{
<div>a.Name</div>
<div>a.Id</div>
<div>a.Link</div>
}

Related

Model returns null when the site first loads

So, I recently found quite an issue with my site: when it first loads, a section of the website is missing. After some tests, I found that this line was sometimes false: #if (Model != null && Model.Any()). After a test using a single Modal == null, I found that yes, the issue is that it's sometimes null. Also, I found that the best way for me to reproduce the issue (no error messages) is to restart visual studio. CTRL + F5 does not make it be null. Any ideas why is that ?
Here's the Model and the part of cshtml:
public class BlogModel
{
public int Id { get; set; }
public bool AfficheAuteur { get; set; }
public string Alias { get; set; }
public string Sujet { get; set; }
public string Auteur { get; set; }
public string Photo { get; set; }
public int? Ordre { get; set; }
public PostModel Post { get; set; }
}
public class PostModel
{
public int Id { get; set; }
public string Alias { get; set; }
public string Nom { get; set; }
}
//.cshtml:
#model IList<Project.Models.Shared.BlogModel>
//...
#if (Model != null && Model.Any())
//...
Note that I'm using asp.net Core MVC with razor.
Edit:
public static IList<BlogModel> GetBlogs()
{
var _lock = new object();
var strKey = string.Format("Home-Blogs-{0}", Site.Id);
var blogs = (IList<BlogModel>)CacheManager.Get(strKey);
if (blogs == null)
{
lock (_lock)
{
blogs = (IList<BlogModel>)CacheManager.Get(strKey);
if (blogs == null)
{
using (var context = new DB())
{
context.Configuration.LazyLoadingEnabled = false;
var nIdSite = Site.Id;
var bl = (from b in context.Blog
where b.Actif &&
(b.IdsSite.Contains("," + nIdSite + ",")) &&
b.Posts.Any(y => y.Publier)
orderby b.Ordre
select new BlogModel()
{
Id = b.Id,
AfficheAuteur = b.AfficherAuteur,
Alias = b.Alias,
Sujet = b.Sujet,
Photo = b.Image,
Auteur = b.User.Profile.FirstName + " " + b.User.Profile.LastName,
Ordre = b.Ordre,
Post = (from p in context.BlogPost
where p.Publier &&
p.IdBlog == b.Id &&
p.DateAffichage <= DateTime.Now
orderby p.DateAffichage descending
select new PostModel()
{
Id = p.Id,
Alias = p.Alias,
Nom = p.Nom
}).FirstOrDefault()
}).ToList();
CacheManager.Insert(strKey, bl, null, 10800, Cache.NoSlidingExpiration, CacheItemPriority.High, null);
return blogs;
}
}
}
}
return blogs;
}
public ActionResult Index(GridSettings settings, string strQuery)
{
var model = new IndexBlogViewModel(settings, blogService, strQuery);
ViewBag.FilAriane.Add(new KeyValuePair<string, string>(Url.Action("Index", "Home"), "Accueil"));
ViewBag.FilAriane.Add(new KeyValuePair<string, string>("", "Blogs"));
return View(model);
}
[HttpGet]
public ActionResult Create()
{
var model = new BlogFormViewModel { Blog = new Entitie.Blog { IdSite = IdSite } };
var lstUser = new List<User>();
var cfUserProvider = new CFUserProvider();
foreach (var mu in cfUserProvider.GetAllUsers().Cast<MembershipUser>())
{
var r = new CFRoleProvider();
if (r.IsUserInRole(mu.UserName, "Bloggeur"))
{
var u = new User { Username = mu.UserName, Id = Convert.ToInt32(mu.ProviderUserKey) };
lstUser.Add(u);
}
}
model.User = lstUser.Select(x => new SelectListItem
{
Text = x.Username,
Value = x.Id.ToString()
});
model.Sites = siteService.GetAll(x => x.IdEntreprise == IdEntreprise)
.Select(x => new CheckBoxListItem
{
Id = x.Id,
Display = x.Nom,
IsChecked = false
}).ToList();
ViewBag.FilAriane.Add(new KeyValuePair<string, string>(Url.Action("Index", "Home"), "Accueil"));
ViewBag.FilAriane.Add(new KeyValuePair<string, string>("", "Blog"));
return View(model);
}
Found it... It was checking for null and if it was, was adding it to cache but still returning the non-updated variable. Simply had to update it before returning...
Added:
blogs = (IList<BlogModel>)CacheManager.Get(strKey);
before returning.

How to Bind a group by data in view in mvc5? what are the best ways to do

I am using Entityframework context, i dont know how to bind to view.
I am grouping items by gender
public SQLChallengeEntities Sqlcontext = new SQLChallengeEntities();
var bookGrouped = Sqlcontext.Empinfoes.ToList()
.GroupBy(x => x.EmpSex).ToList();
return View(bookGrouped.ToList());
In View How to get the data
#foreach (var s in Model)
{
#group.Sex
foreach (var book in s.Values)
{
#s.Empname
#s.EmpDesignation #s.EmpAge
}
}
I am getting this error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[System.Linq.IGrouping2[System.String,Angular‌​CrudS.Empinfo]]', but this dictionary requires a model item of type 'System.Linq.IGrouping2[System.String,AngularCrudS.Empinfo]'
In order to have #group.Sex you need to have a model like
public class EmployeeSexGroupModel
{
public string Sex { get; set; }
public IEnumerable<AngularCrudS.Employee> Employees { get; set; }
}
Then your query would be
var bookGrouped = Sqlcontext.Empinfoes
.GroupBy(x => x.EmpSex).Select(x => new EmployeeSexGroupModel { Sex = x.Key, Employees = x});
return View(bookGrouped.ToList());
Your view would then look like
#model List<EmployeeSexGroupModel>
#foreach (var s in Model)
{
#s.Sex
foreach (var e in s.Employees)
{
#e.Empname
#e.EmpDesignation #e.EmpAge
}
}
public class GroupClass
{
public string Key { get; set; }
public List<Shahriar> shahriarList { get; set; }
}
var list = db.Shahriars.GroupBy(x => x.Name).Select(x => new GroupClass(){
Key = x.Key,
shahriarList = x.ToList()
}).ToList();
ViewBag.Data = list;
#foreach (var x in (List<GroupClass>)ViewBag.Data)
{
<tr><td colspan="4" style="background-color:lightblue;">#x.Key</td></tr>
foreach (var y in x.shahriarList)
{
<tr>
<td>#y.Id</td>
<td>#y.Name</td>
<td>#y.Roll</td>
<td>#y.Mobile</td>
</tr>
}
}

Show images from IQueryable in View

I have a question about showing images loaded from a mysql database in a view.
In my database table "deliverables" I have "item_id", "deliverable_image" and "afstudeerrichting_id". "item_id" and "afstudeerrichting_id" are FK from other tables.
I want to show the images when afstudeerrichting_id = ..
Controller:
public ActionResult Index()
{
var model = repository.GetIdsOfImages(1);
return View(model.ToList());
}
public ActionResult ShowImage(int afstudeerrichtingid)
{
IQueryable<byte[]> data = repository.GetImages(afstudeerrichtingid);
var thedata = data.First();
return File(thedata, "image/png");
}
Repository (where I get the images):
public IQueryable<long> GetIdsOfImages(int afstudeerrichtingid)
{
return from deliverable in entities.deliverables
where deliverable.afstudeerichting_id.Equals(afstudeerrichtingid)
select deliverable.item_id;
}
public IQueryable<byte[]> GetImages(int afstudeerrichtingid)
{
return from deliverable in entities.deliverables
where deliverable.afstudeerichting_id.Equals(afstudeerrichtingid)
select deliverable.deliverable_image;
}
View:
#foreach(var imgID in Model.DeliverablesIDsList)
{
<img src="#Url.Action("ShowImage", "Deliverable", new { DeliverableID = imgID })" />
}
In my Viewmodel:
public List<long> DeliverablesIDsList { get; set; }
public int DeliverableID { get; set; }
Now I get the error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Int64]', but this dictionary requires a model item of type 'GDMfrontEnd.Models.DeliverableViewModel'.
What should I change in my ViewModel? Or what am I doing wrong?
You can do that:
1) pass to the view a list of images' ids, and build list like this
#foreach(var imgId in model.ImgIdsList)
{
<img src="#Url.Action("ShowImage", "Deliverable", new { imageId = imgId })" />
}
2) in controller, which open this view, simply build a ImgIdsList (probably you need a GetIdsOfImagesWithAfstudeerichtingid(int afstudeerrichtingid), which would return a list of int)
3) you should your ShowImage method - not pass afstudeerrichtingid, but unique id of image; of course in this method you should method like GetImageById(int id).

Error loading images from database

I have a question about showing images loaded from a mysql database in an Index view.
In my database table "deliverables" I have "item_id", "deliverable_image" and "afstudeerrichting_id". "item_id" and "afstudeerrichting_id" are FK from other tables.
I want to show the images when afstudeerrichting_id = ..
Controller:
public ActionResult Index()
{
var model = repository.GetIdsOfImages(1);
return View(model.ToList());
}
public ActionResult ShowImage(int id)
{
IQueryable<byte[]> data = repository.GetImages(id);
byte[] firstimage = data.First();
return File(firstimage, "image/png");
}
Repository:
public IQueryable<long> GetIdsOfImages(int afstudeerrichtingid)
{
return from deliverable in entities.deliverables
where deliverable.afstudeerichting_id.Equals(afstudeerrichtingid)
select deliverable.item_id;
}
public IQueryable<byte[]> GetImages(int itemID)
{
return from deliverable in entities.deliverables
where deliverable.item_id.Equals(itemID)
select deliverable.deliverable_image;
}
View:
#foreach(var imgID in Model.DeliverablesIDsList)
{
<img src="#Url.Action("ShowImage", "Deliverable", new { DeliverableID = imgID })" />
}
In my Viewmodel I have:
public List<long> DeliverablesIDsList { get; set; }
public int DeliverableID { get; set; }
But now I always get this error:
he model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Int64]', but this dictionary requires a model item of type 'GDMfrontEnd.Models.DeliverableViewModel'.
Does someone knows what I'm doing wrong?
you're sending to the view a list of int64 repository.GetIdsOfImages(1).ToList() and the view requires a DeliverableViewModel, so you must create a model and put the list into the model and send it to the view
the action should looks like:
public ActionResult Index()
{
var model = repository.GetIdsOfImages(1);
DeliverableViewModel model = new DeliverableViewModel()
model.DeliverablesIDsList = repository.GetIdsOfImages(1).ToList();
return View(model); //send to the view a model type of DeliverableViewModel
}
now with ActionResult ShowImage, the action expect id parmeter and you're sending DeliverableID, so change de var name
public ActionResult ShowImage(int DeliverableID)
{
IQueryable<byte[]> data = repository.GetImages(DeliverableID);
byte[] firstimage = data.First();
return File(firstimage, "image/png");
}

Model Item type ambiguity when using PagedList

I am developing a web survey application in ASP.Net Mvc3. I use PagedList in my application to paginate the questions page alone.
I get the following error:
The model item passed into the dictionary is of type
'PagedList.PagedList`1[SWSSMVC.Models.ViewModels.QuestionViewModel]',
but this dictionary requires a model item of type
'PagedList.IPagedList`1[SWSSMVC.Models.ViewModels.QuestionListViewModel]'.
There is a question which is of similar nature. The solution says not to specify anonymous type, as far as I understood. Can someone point out where in my code I have anonymous type? I believe I have typed all my variables with appropriate models.
This is the question Controller:
public class QuestionController : SessionController
{
DBManager dbmgr = new DBManager();
//
// GET: /Question/
public ActionResult Index(string currentSection, string currentPage, int? page)
{
int j;
SectionSession = currentSection;
PageSession = currentPage;
var questionList = new QuestionListViewModel();
int questionCount = dbmgr.getQuestionCount(currentPage);
var question = new QuestionViewModel();
for(int i=1 ; i<=questionCount; i++)
{
int questionid = dbmgr.getQuestionid(currentPage, i);
string questiontext = dbmgr.getQuestion(questionid);
List<string> oldchoices = dbmgr.getChoicesAns(questionid);
ChoiceViewModel choice = new ChoiceViewModel();
question = new QuestionViewModel { QuestionId = questionid, QuestionText = questiontext, Answer = oldchoices.Last()};
for (j = 0; j < oldchoices.Count() - 1; j++)
{
if (oldchoices[j] != null)
{
question.Choices.Add(new ChoiceViewModel { ChoiceId = j, ChoiceText = oldchoices[j] });
}
}
questionList.Questions.Add(question);
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(questionList.Questions.ToPagedList(pageNumber, pageSize));
}
There are two models:
public class QuestionViewModel
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public List<ChoiceViewModel> Choices { get; set; }
public string Answer { get; set; }
[Required]
public string SelectedAnswer { get; set; }
public QuestionViewModel()
{
Choices = new List<ChoiceViewModel>();
}
}
public class QuestionListViewModel
{
public List<QuestionViewModel> Questions { set; get; }
public QuestionListViewModel()
{
Questions = new List<QuestionViewModel>();
}
}
I am entering my part- Index View code for the above Question Controller
#model PagedList.IPagedList<SWSSMVC.Models.ViewModels.QuestionListViewModel>
#{
ViewBag.Title = "Index";
}
<h2>Questions</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
#foreach (var item in Model)
{
#Html.EditorFor(x => item.Questions)
}
I also have a Editor Template like this
#model SWSSMVC.Models.ViewModels.QuestionViewModel
<div>
#Html.HiddenFor(x => x.QuestionId)
<h3> #Model.QuestionText </h3>
#foreach (var a in Model.Choices)
{
<p>
#Html.RadioButtonFor(b => b.SelectedAnswer, a.ChoiceText) #a.ChoiceText
</p>
}
</div>
I tried to run through the code a couple of times and having hard time figuring it out. I also do not know how I could have made the questionList as a LINQ variable, given that, my questionList is inturn constructed with questions and choices from a separate model.
Creator of PagedList here. The problem is that this line:
return View(questionList.Questions.ToPagedList(pageNumber, pageSize));
Is sending a model of type IPagedList down to the page (because the extension method is being applied to a type of List), but your page says it is expecting:
#model PagedList.IPagedList<SWSSMVC.Models.ViewModels.QuestionListViewModel>
Changing your view code to say this instead should fix it:
#model PagedList.IPagedList<SWSSMVC.Models.ViewModels.QuestionViewModel>

Resources