I have a controller that passes data to my view through the ViewBag
My controller:
var aJobs = from a in gdb.AcceptedJobs
where a.Job.EmployerID == (Guid)Session["UserID"] && !a.Archived
select new { a.Job.Title, a.Job.Address };
ViewBag.jobs = aJobs;
return View("Employer");
My view:
foreach (var job in ViewBag.jobs)
{
#job.Title
#job.Address
}
Now, when i browse to the page i get error object does not contain a definition for Title, at #job.Title, why is this?
I'm using ASP.Net MVC3 C#
Try creating your anonymous type this way
select new { Title = a.Job.Title, Address = a.Job.Address };
When im debugging, and the error is thrown i checked the locals. Then i can clearly see that in the first iteration, the job-object contains a Title-string with the value of my name.
Related
I have an MVC page (Not .Net Core) which contains the below code
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(1))
The query in the address bar is similar to ..../products/product?id=4
How could i pass in the query value of 4 (or whatever it might be) into the Model.Product(ID) which then calls some code in my database to retrieve that product?
Using a hardcoded value works so im not sure if i should be doing this differently or if there is a better approach?
Finally hopefully this wont make a difference but once i have this working i would like to change the URL to something more friendly i.e. ..../products/product/4
method 1 : get route data in razor view
{
var id = Context.GetRouteData().Values["id"];
}
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(id))
method 2 : pass id with controller (viewbag or model)
public ActionResult Product(int id){
var model= {
...
Id = id
}
//ViewBag.Id = id;
return View(model)
}
view:
#model ViewModel
{
var id = int.Parse(ViewBag.Id); // alternative sln.
}
#Html.Partial("~/Views/ProductLanding/product.cshtml", Model.Product(Model.Id))
I have been using the below method and it works for me you can also try this
#Html.Action(, , new { #<Parameter_name> = })
Eg:
#Html.Action("DetailsProducts", "CREDITNOTEs", new { #id = Model.ID })
I'm filling values to a session's like following to retrive those in _LayoutPartial view
if (userdata != null)
{
Session["userdata"] = new SampleViewModel { FirstName = userdata.UserFirstName, LastName = userdata.UserLastName };
FormsAuthentication.SetAuthCookie(loginmodel.UserName, false);
return RedirectToAction("Dashboard", "Home", new { username = loginmodel.UserName });
}
I want to retrive those values in _LayoutPartial View , So I tried somethin like following
<a class="sa">
(#Session["userdata"] as ProjectName.Models.SampleViewModel).FirstName
(#Session["userdata"] as ProjectName.Models.SampleViewModel).LastName
</a>
But this is not retrieving data properly . In this _LoginPartial I'm not Referencing any model also
You have your parenthesis in the wrong spot, and you need a double set - one for the casting (inner set) and one for the razor execution (outer set). It needs to be
#((Session["userdata"] as ProjectName.Models.SampleViewModel).Name)
The following code runs perfectly for creating a SelectList of my Categories.
var categoryList = _context.Category.Select(f => new SelectListItem
{
Value = f.ID.ToString(),
Text = f.CategoryName
});
Now I wanted to default the SelectList with the current category when editing an item.
var categoryList = _context.Category.Select(f => new SelectListItem
{
Value = f.ID.ToString(),
Text = f.CategoryName,
Selected = (f.ID == itemModel.category.ID) // <- added this line
});
But I get this error:
If I just shortcut it for testing purposes like this: Selected = (true) the code runs again without error.
Why would adding the bool check f.ID == itemModel.category.ID cause a model change? Both left and right hand values are int. How can I fix this?
P.S. Just for grins I tried adding a migration and I still get the same error.
LINQ-to-SQL always tries to build a SQL query from your clauses, statements and conditions, and then it runs that query. But in this case it can't convert your code to SQL, because the code refers to an object not available in that context.
Solution:
Replace _context.Category.Select(...) with _context.Category.ToList().Select(...).
The condtions are now evaluated on the List of objects, instead of on the database.
It is because EF is unable to translate that expression in SQL.
The simplest way is to create a SelectList using its constructor overload like:
var categoryList = new SelectList(_context.Category.ToList(),
"ID", // data value field
"CategoryName", // data text field
itemModel.category.ID // selected value
);
I am using Html.Action and PartialView.
I have a linq statement that I know is working correctly.
However when trying to use the Html.Action I am getting a different result from the linq statement.
I am getting this error message
Exception has been thrown by the target of an invocation.
But the really error message is
Duplicate type name within an assembly
I have checked my data, clean my solution and used the Linqer tool to make sure the statement is working correctly. No luck.
Here's what I created.
The html Code
#model #model IEnumerable<MvcCureUrbanNonProfit.Models.PageContent>
#Html.Action("PageContentDisplay", "Home", new { id = 1 })
For the PartialView
#model MvcCureUrbanNonProfit.Models.PageContent
#Html.Raw(#Model.PageContentLongDesc)
For the ActionResult method
public ActionResult PageContentDisplay(int id)
{
var pageContentList = from p in db.PageContents
from w in db.WebSites
where w.WebSiteID == 4 && p.PageTab == 1 && p.PageContentSeqNbr = 1
select p;
return PartialView("_PageContentDisplay", pageContentList);
}
I manager to figure out the issue with the error message. After spending several hours trying to understand the error message it turns out that the problem had to do with having an anonymous type<\b>.
My linq query was returning an IQueryable. I only needed 1 item from the collection. So I added ".First() to return the first element.
[ChildActionOnly]
public ActionResult PageContentDisplay(int id)
{
int webSiteNbr;
bool result = int.TryParse(WebConfigurationManager.AppSettings["WebSite"], out webSiteNbr);
PageTab pageTab = PageTab.Home;
int pageTabVal = (int)pageTab;
var pagContentList2 = from p in db.PageContents
from w in db.WebSites
where w.WebSiteID == webSiteNbr && p.PageTab == pageTabVal && p.PageContentSeqNbr == id
//select p;
select new PageContentVM
{
PageContentID = p.PageContentID,
PageContentLongDesc = p.PageContentLongDesc
};
return PartialView("_PageContentDisplay", pagContentList2.Single());
}
Hi and thanks in advance. I'm having a problem implementing a suggestion that I found here: Convert contents of DataGridView to List in C#
I am grabbing a GridView from a Master page and I need to add a row to the table then rebind it. I am accessing the GridView via a public property on the Master page which is being returned with data. So basically I have done this:
var gsr = master.GridSearchResults;
gsr (gsr != null)
{
var so = new List<MyProperties>();
so = gsr .Rows.OfType<DataGridViewRow>().Select(r => r.Cells.OfType<DataGridViewCell>().Select(c => c.Value).ToArray()).ToList<MyProperties>();
so.Add(new MyProperties()
{
Id = id,
Date = date,
Building = buildingName,
Street = streetName
}
gsr.DataSource = so;
gsr.DataBind();
}
But I'm receiving an error that it cannot convert an instance argument type System.Collections.Generic.IEnumerable<'object[]'> to System.Collections.Generic.IEnumerable<'MyProperties'>. I thought the problem was the call to the array but if I remove it then I just get a variation of the same error.
Turns out my issue was that I shouldn't have been getting the gridview in the first place but getting the the Gridview's source which was in session. So I solved it like this:
var master = (Tab)Master;
master.GridSearchResults.DataSource = null;
var sessions = new Sessions();
sessions.SlideOutSource.Add(new MyProperties {
Id = Id,
StartDate = hidStartDate.Value,
Installation = txtInstall.Text,
Command = txtCommand.Text });
master.GridSearchResults.DataSource = sessions.SlideOutSource;
master.GridSearchResults.DataBind();