MVC 3 model item passed into dictionary error - asp.net-mvc

I get this error and i don't understand why:
The model item passed into the dictionary is of type 'Devart.Data.Linq.DataQuery`1[CHRContext.WIKIIDEE]', but this dictionary requires a model item of type 'CHRContext.WIKIREPARTO'.
method from model
public IQueryable<WIKIIDEE> GetIdeasByDeptID(int id)
{
var query = from i in db.WIKIIDEEs
where i.IDREPARTO == id
select i;
return query;
}
method from controller
public ActionResult List(int id)
{
try
{
IdeeRepository ideeRepo = new IdeeRepository();
IQueryable<WIKIIDEE> list = ideeRepo.GetIdeasByDeptID(id);
return View(list);
}
catch (Exception Ex)
{
return View("Error");
}
}
and view
#model IEnumerable<CHRContext.WIKIIDEE>
#{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>List</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
IDREPARTO
</th>
<th>
DATAINSERIMENTO
</th>
<th>
DESCRIZIONE
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.IDREPARTO)
</td>
<td>
#Html.DisplayFor(modelItem => item.DATAINSERIMENTO)
</td>
<td>
#Html.DisplayFor(modelItem => item.DESCRIZIONE)
</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>

I ran into a very similar issue and was able to work around it. You can see how, here in my answer: The model item passed into the dictionary is of type A, but this dictionary requires a model item of type B

Related

How i can send list of data from two tables to view?

I'm work in asp mvc application database first a broach So i have two tables Employee and Branch and i need to send list to view with Employee name and branch name that's my controller code
public PartialViewResult List()
{
List<Employee> emp;
using (var contxt = new EnglisCenterEntities())
{
var query = contxt.Employee.ToList();
emp = query;
}
return PartialView(emp);
}
and my view code is
#model IEnumerable<Insert.Models.Employee>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.EmpName)
</th>
<th>
#Html.DisplayNameFor(model => model.Phone)
</th>
<th>
#Html.DisplayNameFor(model => model.Username)
</th>
<th>
#Html.DisplayNameFor(model => model.Branches.BranchName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.EmpName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.DisplayFor(modelItem => item.Username)
</td>
<td>
#Html.DisplayFor(modelItem => item.Branches.BranchName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.IdEmp }) |
#Html.ActionLink("Details", "Details", new { id=item.IdEmp }) |
#Html.ActionLink("Delete", "Delete", new { id=item.IdEmp })
</td>
</tr>
}
But it doesn't work so how i can send branch name with employee data
Here is :
public PartialViewResult List()
{
List<Employee> emp;
using (var contxt = new EnglisCenterEntities())
{
var brands = contxt.Employee.Include("Branches").ToList();
// var query = contxt.Employee.ToList();
emp = brands;
}
return PartialView(emp);
}
Thanks guys :)

MVC Object(x) does not contain a definition for blah

Getting an error on the view, at the displaynamefor softwareid line, saying the model SoftwareDTO does not contain a definition for softwareid. I can see it right there in the model.
Model:
public class SoftwareDTO
{
public int SoftwareId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Controller:
public ActionResult Index()
{
List<SoftwareDTO> softwareList = new List<SoftwareDTO>();
var data = _db.Software.ToList();
foreach (var sw in data)
{
SoftwareDTO software = new SoftwareDTO()
{
SoftwareId = sw.SoftwareId,
Name = sw.Name,
Description = sw.Description
};
softwareList.Add(software);
};
return View(softwareList);
}
View:
#model List<Request.Models.SoftwareDTO>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.SoftwareId)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.SoftwareId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
its because model its a list not an object SoftwareDTO in your razor view
I think you are missing the foreach
SoftwareId is a property of SoftwareDTO class. Your view is strongly typed to a collection of SoftwareDTO objects. So you need to loop through the model(The collection of SoftwareDTO) and access the SoftwareId of each item.
#model List<Request.Models.SoftwareDTO>
<table class="table">
#foreach(var item in Model)
{
<tr>
<td>
#Html.DisplayNameFor(x=> item.SoftwareId)
</td>
</tr>
}
</table>
EDIT : As per the edit in the question, and the comments provided.
Looks like you want to print the display name of the propertes in your table headers. If you do not wish to change the data you are passing from your action method, you can try this
#if (Model.Any())
{
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(x => Model[0].SoftwareId)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(x => item.SoftwareId)
</td>
</tr>
}
</table>
}
This is using the first item in the collection and it's properties to use with DisplayNameFor method. Since i have a if condition to check for at least one item before rendering the table, It will not even render the table if your Model has 0 items.
If you want to show the empty table with headers, you have 2 options.
Write HTML markup for the table header
<table class="table">
<tr>
<th>
<label>Software Id</label>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(x => item.SoftwareId)
</td>
</tr>
}
</table>
Or if you still want to use the DisplayNameFor helper method to render the table header labels,
Create a new viewmodel
public class TableListVm
{
public List<SoftwareDTO> Items {set;get;}
public SoftwareDto ItemMeta {set;get;}
public TableListVm()
{
ItemMeta= new SoftwareDto();
}
}
And in your GET action, Send this object to your view
public ActionResult Index()
{
var data = _db.Software.ToList().Select(sw=> new SoftwareDTO {
SoftwareId = sw.SoftwareId,
Name = sw.Name,
Description = sw.Description
}).ToList();
var vm= new TableListVm { Items = data };
return View(vm);
}
And in your view which is strongly typed to this new view model.
#model TableListVm
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(x => Model.ItemMeta.SoftwareId)
</th>
</tr>
#foreach (var item in Model.Items)
{
<tr>
<td>
#Html.DisplayFor(x => item.SoftwareId)
</td>
</tr>
}
</table>

How to highlight a new added entry in MVC?

I've created a DB application in MVC 4 using EntityFramework. It works okay, however I couldn't find the way of highlighting new added item to my table(html). Is it possible to highlight new rows in DB applications in MVC? Like in C#:
DataGrid.SelectedItem
Any advice or help would be very clarifying. How to highlight a row in MVC?
How are you rendering the table?
One option is to use TempData. Store the identifier of the added item in TempData and check for the identifier when rendering the table.
ItemController:
// POST: /Item/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id,Name")] Item item)
{
if (ModelState.IsValid)
{
db.Items.Add(item);
db.SaveChanges();
TempData["AddedItemId"] = item.Id;
return RedirectToAction("Index");
}
return View(item);
}
Item view:
<!-- Views\Item\Index.cshtml -->
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
var className = "";
if (TempData["AddedItemId"] != null && (int)TempData["AddedItemId"] == item.Id)
{
className = "alert-info";
}
<tr class="#className">
<td>
#Html.DisplayFor(modelItem => item.Name)
</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>

Add Search Engine into MVC Music Store

i'm trying to add search the title plus genre drop down list inside store in mvc music store. here's the procedure i've done
firstly i'v added the below code into the StoreManagere controller
public ActionResult SearchIndex(string musicGenre, string searchString)
{
var GenreLST = new List<string>();
var GenreQry = from d in db.Genres
orderby d.Name
select d.Name;
GenreLST.AddRange(GenreQry.Distinct());
ViewBag.movieGenre = new SelectList(GenreLST);
var musics = from m in db.Albums.Include(a => a.Genre).Include(a => a.Artist)
select m;
if (!string.IsNullOrEmpty(searchString))
{
musics = musics.Where(s => s.Title.Contains(searchString));
}
if (string.IsNullOrEmpty(musicGenre))
return View(musics);
else
{
return View(musics.Where(x => x.Genre.Name == musicGenre));
}
}
and the below code inside search index view page
#model IEnumerable<MvcMusicStore.Models.Album>
#{
ViewBag.Title = "SearchIndex";
}
<h2>SearchIndex</h2>
<p>
#Html.ActionLink("Create New", "Create")
#using (Html.BeginForm()) {
<p>Genre : #Html.DropDownList("musicGenre", "All")
Title : #Html.TextBox("searchString")
<input type="submit" value="Filetr" /></p>
}
</p>
<table>
<tr>
<th>
Genre
</th>
<th>
Artist
</th>
<th>
Title
</th>
<th>
Price
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Genre.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Artist.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
#Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
</td>
</tr>
}
</table>
but i get this error
There is no ViewData item of type 'IEnumerable' that has the key 'musicGenre'.
You saved your genre list in ViewBag.movieGenre not musicGenre. That's why it is not working.

how to get data using #Ajax.ActionLink() in ASP.net MVC

i want get data using #Ajax.ActionLink() method. i have tried in the following way
Create.chtml
function UpdatePoDetails() {
document.getElementById("poSearchbtn").href = "/MaterialReceivePO/SearchPO?searchID=" + document.getElementById('POID').value
}
#using (Ajax.BeginForm(new AjaxOptions
{
UpdateTargetId = "searchData",
LoadingElementId = "loading"
}
))
{
<input id="POName" type="text" />
#Ajax.ActionLink("Search", "SearchPO", null, new AjaxOptions
{
UpdateTargetId = "PoDetailsDiv",
HttpMethod = "GET"
},
new
{
onclick = "UpdatePoDetails()" ,
id = "poSearchbtn"
}
)
}
#using (Ajax.BeginForm(new AjaxOptions
{
UpdateTargetId = "MainBody",
LoadingElementId = "loading"
}))
{
<div id="PoDetailsDiv">
</div>
}
Controller method
public ActionResult SearchPO(string searchID)
{
int id = int.Parse(searchID);
List<PurchaseOrderDetailsModel> podetails = (
from c in po.GetPoListDetails(id)
select new PurchaseOrderDetailsModel()
{
PoDetailsID = c.PoDetailsID,
ItemID = c.ItemID.Value,
Quantity = c.Quantity,
UnitPrice = c.UnitPrice,
TotalPrice = c.TotalPrice,
DiscountPer = c.DiscountPer,
FinalPrice = c.FinalPrice,
CurrencyID = c.CurrencyID,
ProductID = c.ItemID.Value,
ProductName = c.ProductName,
ProductCode = c.ProductCode,
Description = c.Description
}
).ToList();
return View("SearchPO",podetails);
}
SearchPO.chtml
#model IEnumerable<ERP_Web.Areas.Inventory.Models.PurchaseOrderDetailsModel>
<table class="grid-table">
<tr>
<th>
Product Name
</th>
<th>
Code
</th>
<th>
Quantity
</th>
<th>
Unit price
</th>
<th>
Total
</th>
<th>
Discount
</th>
<th>
Final price
</th>
<th>
Receive Quantity
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProductCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
#Html.DisplayFor(modelItem => item.UnitPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalPrice)
</td>
<td>
#Html.DisplayFor(modelItem => item.DiscountPer)
</td>
<td>
#Html.DisplayFor(modelItem => item.FinalPrice)
</td>
<td>
#Html.TextBox("reQuantity");
</td>
</tr>
}
</table>
the poblem is when click on the Ajax link the it goes to the Controller. the controller code executes well but at the end to does not Call the SearchPO View when returning. What is wrong in my Code or what i missing. Any help??
#Ajax.ActionLink("Search", "SearchPO", null,
new AjaxOptions{UpdateTargetId = "PoDetailsDiv",HttpMethod = "GET" },new {id = "poSearchbtn"})
I don't understand why you need this onclick = "UpdatePoDetails()"
public ActionResult SearchPO(string searchID)
{
//Do your logic here
//Build Mark-up of the result
string GeneratedMarkUp = BuildMarkUpFOrtheResult();
return Json(GeneratedMarkUp);
}

Resources